159 Longest Substring with At Most Two Distinct Characters

 这两题有一个 trick Minimum Window Substring 非常
像,就是维护一个 "curCount" 代表目前 (i,j) 之间 match
的数量,而通过 hash[] 的正负充当计数器的作用

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.

 参照 k characters: http://www.cnblogs.com/apanda009/p/7261514.html

linkedhashmap可以用来解stream

 

 

 

 

 

 

public int lengthOfLongestSubstringTwoDistinct(String s) {
    int maxSize = 0;
    int j = 0;
    int[] hash = new int[256];
    int distinctCount = 0;
    for(int i = 0; i < s.length(); i++){
        while(j < s.length()){
            if(distinctCount == 2 && hash[s.charAt(j)] == 0)
                break;
            if(hash[s.charAt(j)] == 0) distinctCount ++;
            hash[s.charAt(j++)]++;
        } 
        if(j - i > maxSize){
            maxSize = j - i;
        } 
        hash[s.charAt(i)]--;
        if(hash[s.charAt(i)] == 0) distinctCount --;
    }
    return maxSize;
}            

 可以用hashmap  来替换hash[]

字符串内连续匹配, 连续计数, 连续求最值问题常用窗口类型的指针, 状态常用计数和, 单个计数, hash 中是否存在, 遍历过? 表示, 看题目要求 

posted @ 2017-07-05 21:50  apanda009  阅读(143)  评论(0编辑  收藏  举报