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
今天赶时间 先用一下 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
|