gpt4 book ai didi

python - 找到最长重复的长度?

转载 作者:太空宇宙 更新时间:2023-11-04 06:44:57 24 4
gpt4 key购买 nike

我已经尝试了很多不同的方法来实现这一点,但我不知道我做错了什么。

reps=[]
len_charac=0
def longest_charac(strng)
for i in range(len(strng)):
if strng[i] == strng[i+1]:
if strng[i] in reps:
reps.append(strng[i])
len_charac=len(reps)
return len_charac

最佳答案

请记住,在 Python 中通常不需要计数循环和索引字符串。还有一个内置的 max 函数:

def longest(s):
maximum = count = 0
current = ''
for c in s:
if c == current:
count += 1
else:
count = 1
current = c
maximum = max(count,maximum)
return maximum

输出:

>>> longest('')
0
>>> longest('aab')
2
>>> longest('a')
1
>>> longest('abb')
2
>>> longest('aabccdddeffh')
3
>>> longest('aaabcaaddddefgh')
4

关于python - 找到最长重复的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31084639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com