159. Longest Substring with At Most Two Distinct Characters

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存character->index, 如果map满了(多于2个),则选出map中index最小的,剔除。并保存two pointer, 指向subarray(不多于2个distinct character)的首尾两端

public class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        if(s.length()<1) return 0;
        HashMap index = new HashMap<>();
        int lo = 0, hi = 0, maxLength = 0;
        while(hi2){//remove the leftmost
                int leftMost = s.length();
                for(int i : index.values()){
                    leftMost = Math.min(leftMost, i);
                }
                char c = s.charAt(leftMost);
                index.remove(c);
                lo = leftMost+1;
            }
            maxLength = Math.max(maxLength, hi-lo);
        }
        return maxLength;
    }
}

二刷
思路同上。不过如果是多个distinct character,可以用treemap, 那么可以直接取到index最小的character然后除去

public class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        Map map = new HashMap<>();
        int start = 0, max = 0;
        for(int i=0; i

你可能感兴趣的:(159. Longest Substring with At Most Two Distinct Characters)