1. 程式人生 > >Python 字串中相鄰最長的長度

Python 字串中相鄰最長的長度

基本操作

基本思路就是後面的字元和前面的字元相比,一樣的加一,不一樣的重新開始

程式碼如下

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"?')