
copy https://leetcode-cn.com/problems/implement-strstr/solution/python3-sundayjie-fa-9996-by-tes/
明天补一下
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
def calShiftMat(st):
dic = {}
for i in range(len(st)-1,-1,-1):
if not dic.get(st[i]):
dic[st[i]] = len(st)-i
dic["ot"] = len(st)+1
return dic
if len(needle) > len(haystack):return -1
if needle=="": return 0
dic = calShiftMat(needle)
idx = 0
while idx+len(needle) <= len(haystack):
str_cut = haystack[idx:idx+len(needle)]
if str_cut==needle:
return idx
else:
if idx+len(needle) >= len(haystack):
return -1
cur_c = haystack[idx+len(needle)]
if dic.get(cur_c):
idx += dic[cur_c]
else:
idx += dic["ot"]
return -1 if idx+len(needle) >= len(haystack) else idx
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SvgHBF7L-1640182598465)(C:\Users\CwwwwS\AppData\Roaming\Typora\typora-user-images\image-20211207192659919.png)]](https://img-blog.csdnimg.cn/fa24293e29314b00ae532e13f0704126.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAQ3d3d3d3d3d3cw==,size_20,color_FFFFFF,t_70,g_se,x_16)
今天赶时间 先用一下 in 随便写一下 等有时间再KMP补一下
class Solution:
def repeatedStringMatch(self, a: str, b: str) -> int:
maxLength = len(a * 2 + b)
res = 1
A = a
while len(a) <= maxLength:
if b in a:
return res
else:
res += 1
a += A
return -1
|