返回介绍

solution / 0100-0199 / 0159.Longest Substring with At Most Two Distinct Characters / README_EN

发布于 2024-06-17 01:04:03 字数 3211 浏览 0 评论 0 收藏 0

159. Longest Substring with At Most Two Distinct Characters

中文文档

Description

Given a string s, return _the length of the longest __substring__ that contains at most two distinct characters_.

 

Example 1:

Input: s = "eceba"
Output: 3
Explanation: The substring is "ece" which its length is 3.

Example 2:

Input: s = "ccaabbb"
Output: 5
Explanation: The substring is "aabbb" which its length is 5.

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of English letters.

Solutions

Solution 1

class Solution:
  def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
    cnt = Counter()
    ans = j = 0
    for i, c in enumerate(s):
      cnt[c] += 1
      while len(cnt) > 2:
        cnt[s[j]] -= 1
        if cnt[s[j]] == 0:
          cnt.pop(s[j])
        j += 1
      ans = max(ans, i - j + 1)
    return ans
class Solution {
  public int lengthOfLongestSubstringTwoDistinct(String s) {
    Map<Character, Integer> cnt = new HashMap<>();
    int n = s.length();
    int ans = 0;
    for (int i = 0, j = 0; i < n; ++i) {
      char c = s.charAt(i);
      cnt.put(c, cnt.getOrDefault(c, 0) + 1);
      while (cnt.size() > 2) {
        char t = s.charAt(j++);
        cnt.put(t, cnt.get(t) - 1);
        if (cnt.get(t) == 0) {
          cnt.remove(t);
        }
      }
      ans = Math.max(ans, i - j + 1);
    }
    return ans;
  }
}
class Solution {
public:
  int lengthOfLongestSubstringTwoDistinct(string s) {
    unordered_map<char, int> cnt;
    int n = s.size();
    int ans = 0;
    for (int i = 0, j = 0; i < n; ++i) {
      cnt[s[i]]++;
      while (cnt.size() > 2) {
        cnt[s[j]]--;
        if (cnt[s[j]] == 0) {
          cnt.erase(s[j]);
        }
        ++j;
      }
      ans = max(ans, i - j + 1);
    }
    return ans;
  }
};
func lengthOfLongestSubstringTwoDistinct(s string) (ans int) {
  cnt := map[byte]int{}
  j := 0
  for i := range s {
    cnt[s[i]]++
    for len(cnt) > 2 {
      cnt[s[j]]--
      if cnt[s[j]] == 0 {
        delete(cnt, s[j])
      }
      j++
    }
    ans = max(ans, i-j+1)
  }
  return
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文