用 Python 编写程序,查找包含两个不同元素的最长子字符串的长度

pythonserver side programmingprogramming更新于 2026/1/24 0:44:17

假设我们有一个字符串 s,我们必须找到包含最多 2 个不同字符的最长子字符串的长度。

因此,如果输入为 s = "xyzzy",则输出将为 4,即 "yzzy"是最多包含 2 个唯一字符的最长子字符串。

为了解决这个问题,我们将遵循以下步骤−

  • start := 0

  • c := a map

  • ans := 0

  • for end in range 0 to size of s, do

    • c[s[end]] := c[s[end]] + 1

    • while size of c > 2,执行

      • c[s[start]] := c[s[start]] - 1


      • 如果 c[s[start]] 为 0,则

        • 删除 c[s[start]]

      • start := start + 1

    • ans := ans 和 (end - start + 1) 的最大值

  • 返回 ans

让我们看看下面的实现以便更好地理解 −

示例

class Solution:
   def solve(self, s):
      from collections import Counter
      start = 0
      c = Counter()
      ans = 0
      for end in range(len(s)):
         c[s[end]] += 1
         while len(c) > 2:
            c[s[start]] -= 1
            if not c[s[start]]:
               del c[s[start]]
            start += 1
         ans = max(ans, end - start + 1)
      return ans
ob = Solution()
s = "xyzzy"
print(ob.solve(s))

输入

s = "xyzzy"

输出

4

相关文章


有用资源