Problem
Given a string, find the length of the longest substring without repeating characters.
Example 1:
1 | |
Example 2:
1 | |
Example 3:
1 | |
Explanation 1
-
We need to find out the length of substring, so while looping the character of the input string, we can use the current index subtract the start index of the substring. If there is only 1 character, then current index is 0, so we need to subtract -1 to get length of 1 because $0 - -1 = 1$. So we initialize the start index of the substring we are going to find is -1, in this case we define this start index as a variable
left. So we can find out the length of the substring usingcurrentIndex - left. -
While looping the character of the string, we put the character and its index into a HashMap if we have not seen the character.
-
If we have seen the character before, then we update the substring’s start index
leftto the maximum betweenleftand the index of the character we have seen before. Then, in the hashmap, replace its index to the current index.1
20 1 2 3 "a b b a"- When we see the second
b, we updateleftfrom -1 to 1. Then when we see the seconda, we need to updateleftto the maximum ofleftand the seen character’s index. In this case,leftshould be 1 not 0.
- When we see the second
-
In each iteration, we update the maximum length using
currentIndex - left. -
After we finish the last iteration, we can return the maximum length.
Solution 1
1 | |
Explanation 2
-
We can also solve this problem using sliding window technique. Think of we will maintain a window that contains all unique characters. First initialize
windowStartandwindowEndto 0. Also, initialize a hashset to record the window’s unique characters. -
Loop the
windowEndfrom index 0 to the last index of the input string. While the set contains the current iterated character, we remove the window’s left characterstr[windowStart]and movewindowStart1 step forward, repeat this while loop until the set doesn’t contains the incoming iterated character. Next, we add the iterated character into the set, then calculate the result bemax(res, windowEnd - windowStart + 1).
Solution 2
1 | |