[英]Find the length of the longest substring with no consecutive repeating characters
[英]How to find the length of the longest consecutive repetition of a certain repeating word in a string?
我正在嘗試編寫一個 function 來標識某個單詞在其最長的連續重復中重復了多少次。
我希望下面的 function 打印“5”,因為“hi”這個詞在字符串內部最重復的序列中重復了 5 次。 我怎樣才能做到這一點?
import re
string = 'hihihihihibyebyebyehihihihibyebyebyehihi'
print(len(max(re.compile("(hi+hi)*").findall(string))))
Output:4
IIUC,您可以使用:
max(map(len, re.findall('(?:hi)+', string)))//len('hi')
Output: 5
或者,如果您的匹配長度可能可變。 捕獲但單元塊和與重復的總匹配:
string = 'hxihxihxihxihxibyebyebyehihihihibyebyebyehihi'
max(len(a)//len(b) for a,b in re.findall('((hx?i)+)', string))
# 5
我建議從正則表達式部分開始。 它可能沒有做你認為它正在做的事情。
出於好奇,我只跑了最后一行的一部分:
re.compile("(hi+hi)*").findall(string)
結果是:
['hihi', '', '', '', '', '', '', '', '', '', '', '', 'hihi', '', '', '', '', '', '', '', '', '', 'hihi', '']
我現在可以看到為什么 output 是 4:這個列表中最長的字符串是 4 個字符長。
這個意想不到的結果提出了幾個問題:
"(hi+hi)*"
實際匹配的模式是什么,為什么?"hihi"
,只有 2 個hi
,但 output 是 4 個。為什么? 嘗試仔細查看正則表達式的文檔,我想您會發現您正在尋找的表達式是"(?:hi)+"
,這大致意味着〜至少重復一次“hi”〜
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.