实现strStr()
刷题日期:2024-04-25
[[028. 实现 strStr()]]
思路
KMP算法
算法思路
先计算前缀表, 再逐个匹配
算法细节
1. 计算前缀表和匹配过程中匹配失败
失败要一直往前走
Code
class Solution:
def cal_pre(self, strs):
prefix = [0] * len(strs)
i = 0
j = 1
while j < len(strs):
if strs[i] != strs[j]:
while i > 0 and strs[i] != strs[j]:
i = prefix[i - 1]
if strs[i] == strs[j]:
prefix[j] = 1 + i
i += 1
j += 1
return prefix
def strStr(self, haystack: str, needle: str) -> int:
prefix = self.cal_pre(needle)
j = 0
for i in range(len(haystack)):
while haystack[i] != needle[j] and j > 0:
j = prefix[j - 1]
if haystack[i] == needle[j]:
j += 1
if j == len(needle):
return i - j + 1
return -1
重复的子字符串
刷题日期:2024-04-25
[[459.重复的子字符串]]
思路
KMP算法
算法思路
通过计算前缀表可知, 如果字符串可以由字串构成, 那么前缀表最后一位不为0, 并且前缀表最后一位的值是前缀表中0的数量的整数倍
算法细节
1.
Code
class Solution:
def cal_pre(self, strs):
prefix = [0] * len(strs)
i = 0
j = 1
while j < len(strs):
if strs[i] != strs[j]:
while i > 0 and strs[i] != strs[j]:
i = prefix[i - 1]
if strs[i] == strs[j]:
prefix[j] = 1 + i
i += 1
j += 1
return prefix
def repeatedSubstringPattern(self, s: str) -> bool:
prefix = self.cal_pre(s)
if prefix[-1] == 0:
return False
temp = len(s) - prefix[-1]
if prefix[-1] % temp == 0:
return True
else:
return False