查找最长子字符串的长度的程序,该子字符串在Python中具有两个不同的元素
假设我们有一个字符串s,我们必须找到包含最多2个不同字符的最长子字符串的长度。
因此,如果输入类似于s=“xyzzy”,则输出将为4,因为“yzzy”是最长的子字符串,最多包含2个唯一字符。
为了解决这个问题,我们将按照以下步骤操作:
开始:=0
c:=映射
回答:=0
对于范围从0到s的大小,请执行
c[s[start]]:=c[s[start]]-1
如果c[s[start]]为0,则
开始:=开始+1
删除c[s[start]]
c[s[end]]:=c[s[end]]+1
当c>2的大小时
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