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

时间:2020-04-10 16:36:55

标签: python string

我想编写一个函数,在该函数中它接收一个字符串和一个字母。该函数需要返回此字母最长子字符串的长度。我不知道为什么我写的功能不起作用 例如: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

4 个答案:

答案 0 :(得分:0)

由于条件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

答案 1 :(得分:0)

我可能建议在re.findall处使用正则表达式:

def count_longest_repetition(s, c):
    matches = re.findall(r'' + c + '+', s)
    matches = sorted(matches, key=len, reverse=True)
    return len(matches[0])

cnt = count_longest_repetition('eabbaaaacccaaddd', 'a')
print(cnt)

此打印:4

为更好地解释上述内容,给定显示的输入,使用的正则表达式为a+,即查找一个或多个a字符的组。调用re.findall的排序列表结果为:

['aaaa', 'aa', 'a']

通过按字符串长度的降序排序,我们将最长的匹配项推到列表的前面。然后,我们从函数中返回该长度。

答案 2 :(得分:0)

这也可以通过groupby

完成
from itertools import groupby
def count_longest_repetition(text,let):
    return max([len(list(group)) for key, group in groupby(list(text)) if key==let])



count_longest_repetition("eabbaaaacccaaddd",'a')

#returns 4

答案 3 :(得分:0)

您的函数不起作用,因为if s[i] in lst:最初将返回false,并且永远不会将任何内容添加到lst列表中(因此它将在整个循环中保持false)。

您应该研究用于此类字符串处理/搜索的正则表达式:

import re
def count_longest_repetition(s, c):
    return max((0,*map(len,re.findall(f"{re.escape(c)}+",s))))

如果不允许使用库,则可以通过将匹配项添加到在每次不匹配时重置的计数器上来计算重复而无需使用列表:

def count_longest_repetition(s, c):
    maxCount = count = 0
    for b in s:
        count = (count+1)*(b==c)
        maxCount = max(count,maxCount)
    return maxCount