159. Longest Substring with At Most Two Distinct Characters - Hard

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.

 

3. Longest Substring Without Repeating Characters - Medium 类似,用counter计数,如果map中对应value == 1,说明这是一个新的字符,counter++。当counter > 2时进入while循环开始移动slow。更新map中slow对应字符的value(-1),如果更新完value为0,counter--。

time: O(n), space: O(n)

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

        int slow = 0, fast = 0, counter = 0, d = 0;
        while(fast < s.length()) {
            char c = s.charAt(fast);
            map.put(c, map.getOrDefault(c, 0) + 1);
            if(map.get(c) == 1)
                counter++;
            fast++;
            
            while (counter > 2) {
                char tmp = s.charAt(slow);
                map.put(tmp, map.get(tmp) - 1);
                if (map.get(tmp) == 0)
                    counter--;
                slow++;
            }
            d = Math.max(d, fast - slow);
        }
        return d;
    }
}

 

另一种写法:

class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        if(s == null || s.length() == 0) {
            return 0;
        }
        Map<Character, Integer> map = new HashMap<>();
        int slow = 0, fast = 0, counter = 0, len = 0;
        while(fast < s.length()) {
            char f = s.charAt(fast);
            map.put(f, map.getOrDefault(f, 0) + 1);
            fast++;
            
            while(map.size() > 2) {
                char c = s.charAt(slow);
                map.put(c, map.get(c) - 1);
                if(map.get(c) == 0) {
                    map.remove(c);
                }
                slow++;
            }
            len = Math.max(len, fast - slow);
        }
        return len;
    }
}

 

posted @ 2019-01-22 10:24  fatttcat  阅读(159)  评论(0编辑  收藏  举报