class Solution:
def strStr(self, haystack: str, needle: str) -> int:
a = len(haystack)
b = len(needle)
if b == 0:
return 0
next = self.getnext(b,needle)
j=0
for i in range(a):
while haystack[i]!=needle[j] and j>0:
j = next[j-1] # 若不相等,则借助next数组寻找下一个j的位置
if haystack[i]==needle[j]:
j += 1
if j == b: #判断是否遍历完模式串needle
return i-b+1
return -1
def getnext(self,b,needle): #得到next数组
j = 0
next = [0 for x in range(b)]
for i in range(1,b):
while(j > 0 and needle[j]!=needle[i]):
j = next[j-1]
if needle[j]==needle[i]:
j += 1
next[i] = j
return next
Leetcode 28. 实现 strStr() Implement strStr() - Python - KMP算法
最新推荐文章于 2022-03-29 23:05:46 发布