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

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 ans(String st) {
          int[] hash1 = new int[128];
          int[] hash2 = new int[128];
          for(char c : st.toCharArray()) {
              hash1[c]++;
              hash2[c]++;
          }
          int res = -1;
          int l = 0;
          int count = 0;
          for(int r = 0; r < st.length(); r++) {
              char c = st.charAt(r);
              if(hash1[c] == hash2[c]) {
                  count++;
              }
              hash2[c]--;
              
              while(count > 2) {
                  hash2[st.charAt(l)]++;
                  if(hash2[st.charAt(l)] == hash1[st.charAt(l)]) count--;
                  l++;
              }
            res = Math.max(res, r - l + 1);
          }
          return res;
    }

可变长度sliding window,注意判断条件,这里count可以作为window里distinct字母的数量,大于2就要缩小,这样保证了没有多余字符进去的可能。

或者用一个array来表示hash

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

https://www.1point3acres.com/bbs/thread-544207-1-1.html

标签:count,159,++,Two,st,Most,int,hash2,sArr
来源: https://www.cnblogs.com/wentiliangkaihua/p/16584727.html