gpt4 book ai didi

python - 计算相同字符的最大子串

转载 作者:行者123 更新时间:2023-12-05 05:04:21 24 4
gpt4 key购买 nike

我想编写一个函数,在其中接收一个字符串 (s) 和一个字母 (s)。该函数需要返回该字母的最长子串的长度。我不知道为什么我写的函数不起作用例如:print(count_longest_repetition('eabbaaaacccaaddd', 'a') 应该返回 '4'

    def count_longest_repetition(s, c):
n= len(s)
lst=[]
length_charachter=0
for i in range(n-1):
if s[i]==c and s[i+1]==c:
if s[i] in lst:
lst.append(s[i])
length_charachter= len(lst)
return length_charachter

最佳答案

由于条件 if s[i] in lst,“lst”将不会附加任何内容,因为最初“lst”是空的,并且永远不会满足 if 条件。此外,要遍历整个字符串,您需要使用 range(n),因为它会生成从 0 到 n-1 的数字。这应该工作 -

def count_longest_repetition(s, c):
n= len(s)
length_charachter=0
max_length = 0
for i in range(n):
if s[i] == c:
length_charachter += 1
else:
length_charachter = 0
max_length = max(max_length, length_charachter)

return max_length

关于python - 计算相同字符的最大子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61144639/

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