Longest Substring with At Most Two Distinct Characters

题目地址:
https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/#/description

题目:
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.

解题思路:
这道题也需要map,只不过map存的是每个char最后出现的index。

代码:

public int lengthOfLongestSubstringTwoDistinct(String s) {
    if(s.length() < 1){
        return 0;
    }
    Map<Character, Integer> map = new HashMap<Character, Integer>();
    int left = 0, right = 0;
    int maxLen = 0;
    while(right < s.length()){
        if(map.size() <= 2){
            char c = s.charAt(right);
            map.put(c, right);
            right++;
        }
        if(map.size() > 2){
            int maxLeft = s.length();
            for(int i : map.values()){
                maxLeft = Math.min(maxLeft, i);
            }
            char c = s.charAt(maxLeft);
            map.remove(c);
            left = maxLeft + 1;
        }
        maxLen = Math.max(maxLen, right - left);
    }
    return maxLen;
}

Comments

Popular Posts