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

159. Longest Substring with At Most Two Distinct Characters

时间:2022-08-14 06:22:05浏览次数:77  
标签:count 159 ++ Two st Most int hash2 sArr

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
From: https://www.cnblogs.com/wentiliangkaihua/p/16584727.html

相关文章