Python 字符串中相邻最长的长度

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010095372/article/details/79328828

基本操作

基本思路就是后面的字符和前面的字符相比,一样的加一,不一样的重新开始

代码如下

import string
def long_repeat(line):
    """
        length the longest substring that consists of the same char
    """
    # 把特殊的提出去
    if len(line) == 0:
        return 0
    #初始化两个参数
    jishu = 1
    t = 0
    # 循环
    for i in range(1,len(line)):
    #不一样的时候,就改重新计算了,但是看看这次的和保存的比较一下,保留大的
        if line[i] != line[i-1]:
            if t < jishu:
                t = jishu  
            jishu = 1
    #一样的往后加
        else:
            jishu = jishu + 1
    return max(t,jishu)

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert long_repeat('sdsffffse') == 4, "First"
    assert long_repeat('ddvvrwwwrggg') == 3, "Second"
    print('"Run" is good. How is "Check"?')

看看外国大神的

from itertools import groupby

def long_repeat(line):
    return max((sum(1 for _ in g) for k, g in groupby(line)), default=0)

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert long_repeat('sdsffffse') == 4, "First"
    assert long_repeat('ddvvrwwwrggg') == 3, "Second"
    print('"Run" is good. How is "Check"?')

猜你喜欢

转载自blog.csdn.net/u010095372/article/details/79328828
今日推荐