题目:
题解:
class Solution:def strStr(self, haystack: str, needle: str) -> int:# Func: 计算偏移表def calShiftMat(st):dic = {}for i in range(len(st)-1,-1,-1):if not dic.get(st[i]):dic[st[i]] = len(st)-idic["ot"] = len(st)+1return dic# 其他情况判断if len(needle) > len(haystack):return -1if needle=="": return 0# 偏移表预处理 dic = calShiftMat(needle)idx = 0while idx+len(needle) <= len(haystack):# 待匹配字符串str_cut = haystack[idx:idx+len(needle)]# 判断是否匹配if str_cut==needle:return idxelse:# 边界处理if idx+len(needle) >= len(haystack):return -1# 不匹配情况下,根据下一个字符的偏移,移动idxcur_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