字符串匹配KMP算法 时间复杂度为O(n+m),其中n为模式串的长度,m为待匹配串的长度。 空间复杂度为O(m),其中m为待匹配串的长度。 12345678910111213141516171819202122232425262728293031323334353637class Solution: def strStr(self, haystack: str, needle: str) -> int: next = self.build_next(needle) i = 0 j = 0 while i < len(haystack): if haystack[i] == needle[j]: i += 1 j += 1 elif j == 0: # 如果j为0,则i+1,继续匹配 i += 1 else: # 如果j不为0,则j=next[j-1],继续匹配 j = next[j-1] if j == len(needle): return i - j return -1 def build_next(self, patt): next = [0] * len(patt) prefix_len = 0 i = 1 while i < len(patt): if patt[prefix_len] == patt[i]: # 如果当前字符与前缀字符相同,则前缀长度+1,i+1 prefix_len += 1 next[i] = prefix_len i += 1 elif prefix_len != 0: # 如果当前字符与前缀字符不同,则前缀长度回退到上一个相同字符的位置 prefix_len = next[prefix_len-1] else: next[i] = 0 i += 1 return next