思路
用KMP算法中的最长相同前后缀解题,涉及next数组
- 先求出字符串的next数组,next数组中存放最长相同前后缀的长度
- 若前缀表不减1,next[len-1]!=0,表示字符串有最长相同的前后缀,同时,len%(len-next[len-1])==0, 表示该字符串有重复的字符串;其中len-next[len-1]表示第一个周期的长度,若可以被len整除,表示整个数组是这个周期的循环;
- 若前缀表减1,next[len-1]!=-1,表示字符串有最长相同的前后缀,同时,len%(len-(next[len-1]+1))==0,表示该字符串有重复的子字符串;next[len-1]+1才是最长相同前后缀,因为前缀表减1了,其他同2.
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
n=len(s)
if n==0:
return False
next=['']*n
next=self.getNext(next,s)
#有最长相同前后缀,且数组长度可以整除一个周期的长度
if next[n-1]!=0 and n%(n-next[n-1])==0:
return True
return False
def getNext(self,next,s):
#前缀表不减1
j=0
next[0]=0
#从1开始,i表示后缀的尾部位置
for i in range(1,len(s)):
while j>0 and s[i] != s[j]:
#字符不相等,回退
j=next[j-1]
if s[i]==s[j]:
j+=1
next[i]=j
return next