|
| 1 | +package solutions; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +// [Problem] https://leetcode.com/problems/longest-substring-without-repeating-characters |
| 7 | +class LongestSubstringWithoutRepeatingCharacters { |
| 8 | + // Sliding window with HashMap |
| 9 | + // O(n) time, O(n) space |
| 10 | + public int lengthOfLongestSubstring(String s) { |
| 11 | + Map<Character, Integer> occurrences = new HashMap<>(); |
| 12 | + int left = 0, maxLength = 0; |
| 13 | + for (int right = 0; right < s.length(); right++) { |
| 14 | + char c = s.charAt(right); |
| 15 | + Integer occurrence = occurrences.get(c); |
| 16 | + if (occurrence != null && occurrence >= left) { |
| 17 | + left = occurrence + 1; |
| 18 | + } |
| 19 | + occurrences.put(c, right); |
| 20 | + maxLength = Math.max(maxLength, right - left + 1); |
| 21 | + } |
| 22 | + return maxLength; |
| 23 | + } |
| 24 | + |
| 25 | + // Test |
| 26 | + public static void main(String[] args) { |
| 27 | + LongestSubstringWithoutRepeatingCharacters solution = new LongestSubstringWithoutRepeatingCharacters(); |
| 28 | + |
| 29 | + String input1 = "abcabcbb"; |
| 30 | + int expectedOutput1 = 3; |
| 31 | + int actualOutput1 = solution.lengthOfLongestSubstring(input1); |
| 32 | + System.out.println("Test 1 passed? " + (expectedOutput1 == actualOutput1)); |
| 33 | + |
| 34 | + String input2 = "bbbbb"; |
| 35 | + int expectedOutput2 = 1; |
| 36 | + int actualOutput2 = solution.lengthOfLongestSubstring(input2); |
| 37 | + System.out.println("Test 2 passed? " + (expectedOutput2 == actualOutput2)); |
| 38 | + } |
| 39 | +} |
0 commit comments