题目:
Given a string, find the length of the longest substring T that contains at most 2 distinct characters.

For example, Given s = “eceba”,

T is "ece" which its length is 3.

解法:

//最重要的是把最后一次出现的这个char的index记在hashmap的value里面。所以当出现不止两个distinc的数的时候,把这个value最低的char删掉,把最lo的index加1就可以啦
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        if (s.length() < 1) return 0;
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        int lo = 0;
        int hi = 0;
        int maxLength = 0;
        
        for (int i = 0; i < s.length(); i++) {
            if (map.size() <= 2) {
                char c = s.charAt(i);
                map.put(c, i);
                hi++;
            }
            if (map.size() > 2) {
                int leftMost = s.length();
                for (int value : map.values()) {
                    leftMost = Math.min(leftMost, value);
                }
                lo = leftMost + 1;
                char c = s.charAt(leftMost);
                map.remove(c);
            }
            maxLength = Math.max(maxLength, hi - lo);
        }
        
        return maxLength;
    }

guoluona
199 声望14 粉丝