其他分享
首页 > 其他分享> > LeetCode 159 Longest Substring with At Most Two Distinct Characters

LeetCode 159 Longest Substring with At Most Two Distinct Characters

作者:互联网

Given a string s , find the length of the longest substring t  that contains at most 2 distinct characters.

Example 1:

Input: "eceba"
Output: 3
Explanation: tis "ece" which its length is 3.

Example 2:

Input: "ccaabbb"
Output: 5
Explanation: tis "aabbb" which its length is 5.
public int lengthOfLongestSubstringTwoDistinct(String s) {
    if (s == null || s.length() == 0) {
        return 0;
    }
     
    char[] sArr = s.toCharArray();
     
    int[] hash = new int[256];
     
    int l = 0, count = 0, result = 1;
    for (int r = 0; r < sArr.length; ++r) {
        hash[sArr[r]]++;
         
        if (hash[sArr[r]] == 1) {
            count++;
        }
         
        while (count > 2) {
            hash[sArr[l]]--;
 
            if (hash[sArr[l]] == 0) {
                count--;
            }
 
            l++;
        }
         
        result = Math.max(result, r - l + 1);
    }
     
    return result;
}

 

标签:count,hash,159,Two,Substring,int,length,result,sArr
来源: https://www.cnblogs.com/wentiliangkaihua/p/13599727.html