Problem
Given a string s , find the length of the longest substring t that contains at most 2 distinct characters.
Example 1:
1 | |
Example 2:
1 | |
Explanation 1
- First, we can create a HashMap, and use it to store the key is the character, the value is the frequency of the character. Also, we initialize the
leftbe 0. Iterate the input string and update the hashmap. While the hashmap has size greater than 2, then we need to decrease the frequency of characters[left]and increase left by 1. Also if thes[left]’s frequency is 0, we remove the keys[left]from the hashmap. Repeat these steps until the hashmap has size less than or equal to 2. Next, we update the result bemax(res, i-left+1).
Solution 1
1 | |
Explanation 2
-
We can optimize the last solution by not using HashMap. First, we create two variables
firstmeans the first distince character,secondmeans the second distince character. Also, we initializecurLenmeans the current 2 distinct character substring’s length, andcntSecondmeans the number of consecutive second characters. -
Iterate the input string’s characters. If the current character is the same as either character
firstor charactersecond, we updatecurLen = curLen + 1, else, we updatecurLen = cntSecond + 1. -
Then, we try to update
cntSecond. If the current character is the same as charactersecond, thencntSecond = cntSecond + 1, elsecntSecond = 1. -
Next, we try to update
firstandsecond. If the current character is not the same assecond, then we updatefirstbe the originalsecondandsecondbe the current character. -
Next, we update the result
res = max(res, curLen).
Solution 2
1 | |