Skip to main content
 首页 » 编程设计

python之找到最长重复的长度

2025年05月04日13lautakyan007

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

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