159 Longest Substring with At Most Two Distinct Characters

Posted apanda009

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了159 Longest Substring with At Most Two Distinct Characters相关的知识,希望对你有一定的参考价值。

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

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;
}            

  

以上是关于159 Longest Substring with At Most Two Distinct Characters的主要内容,如果未能解决你的问题,请参考以下文章

[LC] 159. Longest Substring with At Most Two Distinct Characters

[LeetCode] 159. Longest Substring with At Most Two Distinct Characters

算法159题 Longest Substring with at Most Two Distinct Characters 最大的子串

leetcode 159. Longest Substring with At Most Two Distinct Characters 求两个字母组成的最大子串长度 --------- jav

[LeetCode] 340. Longest Substring with At Most K Distinct Characters

[LeetCode] 340. Longest Substring with At Most K Distinct Characters 最多有K个不同字符的最长子串