【Python CheckiO 题解】Long Repeat
CheckiO 是面向初學者和高級程序員的編碼游戲,使用 Python 和 JavaScript 解決棘手的挑戰和有趣的任務,從而提高你的編碼技能,本博客主要記錄自己用 Python 在闖關時的做題思路和實現代碼,同時也學習學習其他大神寫的代碼。
CheckiO 官網:https://checkio.org/
我的 CheckiO 主頁:https://py.checkio.org/user/TRHX/
CheckiO 題解系列專欄:https://itrhx.blog.csdn.net/category_9536424.html
CheckiO 所有題解源代碼:https://github.com/TRHX/Python-CheckiO-Exercise
題目描述
【Long Repeat】:給定一個字符串,找到字符串中最長的相同字符重復出現的次數,并返回它的重復次數。例如:字符串“aaabbcaaaa”包含具有相同字母“aaa”,“bb”,“c”和“aaaa”的四個子字符串。 最后一個子字符串是最長的一個字符串,你應該返回 4 。
【鏈接】:https://py.checkio.org/mission/long-repeat/
【輸入】:一個字符串
【輸出】:一個整數
【范例】:
long_repeat('sdsffffse') == 4 long_repeat('ddvvrwwwrggg') == 3解題思路
遍歷字符串,如果前一個字符與后一個字符相同,就將其出現的次數加一,同時,每次遍歷都用 max() 方法記錄字符出現次數最多的
代碼實現
def long_repeat(line: str) -> int:new_string = ''num = 0max_num = 0for string in line:if string != new_string:new_string = stringnum = 1else:num += 1max_num = max(max_num, num)return max_numif __name__ == '__main__':# These "asserts" using only for self-checking and not necessary for auto-testingassert long_repeat('sdsffffse') == 4, "First"assert long_repeat('ddvvrwwwrggg') == 3, "Second"assert long_repeat('abababaab') == 2, "Third"assert long_repeat('') == 0, "Empty"print('"Run" is good. How is "Check"?')大神解答
大神解答 NO.1
from itertools import groupbydef long_repeat(line):return max((sum(1 for _ in g) for k, g in groupby(line)), default=0)大神解答 NO.2
def long_repeat(line):m=0p=0for x in range(len(line)):if x<len(line)-1:if line[x]==line[x+1]:p+=1else:p=0if p+1>m:m=p+1return m 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的【Python CheckiO 题解】Long Repeat的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 二手车重大利好政策发布!8月1日起全面取
- 下一篇: Python3 爬虫学习笔记 C13【验