159. Longest Substring with At Most Two Distinct Characters 159.最长两个不同字符的子字符串

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.


不是counter > 2就要返回,而是counter > 2就要控制

只有出现了一次的新字母需要控制,所以只有
if(map.get(c) == 1) counter++;
if(map.get(cTemp) == 0)时counter--; 

 

public class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        Map<Character, Integer> map = new HashMap<>();
        int begin = 0, end = 0, counter = 0, d = 0;

        while (end < s.length()) {
            char c = s.charAt(end);
            map.put(c, map.getOrDefault(c, 0) + 1);
            if(map.get(c) == 1) counter++;
            end++;
            
            while (counter > 2) {
                char charTemp = s.charAt(begin);
                map.put(charTemp, map.get(charTemp)-1);
                if (map.get(charTemp) == 0) counter--;                
                begin++;

            }
            if (end - begin > d) 
                d = end - begin;
        }
        return d;
    }
}
View Code

 

posted @ 2020-07-31 23:22  苗妙苗  阅读(123)  评论(0编辑  收藏  举报