我尝试了许多不同的方法来实现此目的,但我不知道我做错了什么。

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

08-24 12:44