如何查找最長連續字符串

查找最長連續子字符串,子字符串須滿足:由連續同字符組成

# 統計結果:字符:連續出現最多的次數
result = {}

# 統計連續出現的字符
def test(s):
    count = 0
    for c in s:
        if c == s[0]:
            count+=1
        else:
            break

    # 只統計最多出現的次數
    if result.get(s[0],0) < count:
        result[s[0]] = count

s1 = 'abbbbbbcccddddddddddddddddeee'
index = 0
while index<len(s1):
    substr = s1[index:]
    test(substr)
    index+=1

print('統計結果',result)

# 對結果進行排序
result_order = sorted(result.items(),key=lambda x:x[1],reverse=True)
print(result_order)
print(result_order[0])

運行結果:

統計結果 {'a': 1, 'b': 6, 'c': 3, 'd': 16, 'e': 3}
[('d', 16), ('b', 6), ('c', 3), ('e', 3), ('a', 1)]
('d', 16)

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章