ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

159. Longest Substring with At Most Two Distinct Characters

2022-08-14 06:30:27  阅读:176  来源: 互联网

标签: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
来源: https://www.cnblogs.com/wentiliangkaihua/p/16584727.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有