28.找出字符中的第一个下标
class Solution:#前缀表不减一
def getnext(self,next,s):#构建next数组
j=0
next[0]=0#初始化
for i in range(1,len(s)):#i代表后缀,j表示前缀
while j>0 and s[i]!=s[j]:#注意是while
j=next[j-1]
if s[i]==s[j]:
j+=1#如果字符相等,比较下一位
next[i]=j#给此时的i赋值
def strStr(self, haystack: str, needle: str) -> int:
if len(needle)==0:#neddle是子串
return 0
next=[0]*len(needle)#创建空数组
self.getnext(next,needle)
#开始扫描
j=0
for i in range(len(haystack)):
while j>0 and haystack[i]!=needle[j]:
j=next[j-1]
if haystack[i]==needle[j]:
j+=1
if j==len(needle):
return i-len(needle)+1#返回长度,一定不会超出子串长度
return -1
class Solution:#前缀表减一
def getnext(self,next,s):#构建next数组
j=-1
next[0]=j
for i in range(1,len(s)):
while j>=0 and s[i]!=s[j+1]:
j=next[j]
if s[i]==s[j+1]:
j+=1#在匹配时之前的基础上加一
next[i]=j#把j赋值给next数组
def strStr(self, haystack: str, neddle: str) -> int:
if not neddle:
return 0
next=[0]*len(neddle)
self.getnext(next,neddle)
j=-1
for i in range(len(haystack)):
while j>=0 and haystack[i]!=neddle[j+1]:
j=next[j]
if haystack[i]==neddle[j+1]:
j+=1
if j==len(neddle)-1:
return i-len(neddle)+1
return -1
next 前缀表:原封不动,看前一位,本位为最大前缀;整体右移,看本位
j还代表了i之前包括i 这个子串的最长相等的前后缀的长度
459.重复的子字符串
数组长度减去最长相同前后缀的长度相当于是第一个周期的长度,也就是一个周期的长度,如果这个周期可以被整除,就说明整个数组就是这个周期的循环。
def repeatedSubstringPattern(self, s: str) -> bool:
n=len(s)
if n<=1:
return False
ss=s[1:]+s[:-1]#两串相同的合并起来
#
return ss.find(s)!=-1