159. Longest Substring with At Most Two Distinct Characters
Given a string s , find the length of the longest substring t that contains at most 2 distinct characters.
Example 1:
Input: "eceba"
Output: 3
Explanation: tis "ece" which its length is 3.
Example 2:
Input: "ccaabbb"
Output: 5
Explanation: tis "aabbb" which its length is 5.
Solution
public int lengthOfLongestSubstringTwoDistinct(String s) {
HashMap<Character, Integer> countRecord = new HashMap<>();
int startIndex = 0, maxLength = 0;
for (int i = 0; i < s.length(); i++) {
countRecord.put(s.charAt(i), countRecord.getOrDefault(s.charAt(i), 0) + 1);
//Remeber 改變startIndex的判斷要用while
while (countRecord.size() > 2) {
//always keep the hashMap only has two set for 2 distinct characters
//move the startIndex to next one, and decease the count value in map accordingly.
countRecord.put(s.charAt(startIndex), countRecord.get(s.charAt(startIndex) - 1));
if (countRecord.get(s.charAt(startIndex)) == 0) {
//remove the set if the count is 0
countRecord.remove(s.charAt(startIndex));
}
startIndex++;
}
maxLength = Math.max(maxLength, i - startIndex + 1);
}
return maxLength;
}
Last updated
Was this helpful?