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

标签 python python-3.x

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

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/

相关文章:

python - Python itertools `constant_factory` 示例如何优于 `lambda : x` ?

python - 使用 Python 进行 URL 编码/解码

python-3.x - Kubernetes Python 客户端连接问题

python - 如何在 django 中应用 postman 过滤器?

python - (Python) PyInstaller unicode 错误

python - Flask-admin:捕获 inline_models 上的更改

python - OpenCV:FFMPEG:标签 0x34363268/'h264' 不支持编解码器

python - 表解析如何在 python 中工作?除了那道漂亮的汤,还有什么简单的方法吗?

python - Jupyter Notebook 不记得我在上面的单元格中创建的变量

python - pip3 install Flask-MongoEngine 安装失败