很明显的2 pointer问题。。。当满足条件的时候后面的指针加,不满足条件的时候前面的指针加,直到满足条件。。。

class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        int start = 0, cnt = 0;
        int char_set[256] = {0};
        int ans = 0;
        for (int i = 0; i < s.size(); i++) {
            if (char_set[s[i]]++ == 0) cnt++;
            while (cnt > 2) {
                char_set[s[start]]--;
                if (char_set[s[start++]] == 0) cnt--;
            }
            ans = max(i - start + 1, ans);
        }
        return ans;
    }
};

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-03
  • 2021-08-01
猜你喜欢
  • 2021-10-23
  • 2022-12-23
  • 2021-12-29
  • 2022-12-23
  • 2022-12-23
  • 2021-11-23
  • 2021-10-14
相关资源
相似解决方案