28. 实现 strStr()
题目描述
给定一个字符串,逐个翻转字符串中的每个单词。
说明:
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
原题请参考链接https://leetcode-cn.com/problems/implement-strstr
题解
方法一 【kmp算法】
class Solution:
def gen_pnext(self,substring):
index, m = 0, len(substring)
pnext = [0]*m
i = 1
while i < m:
if (substring[i] == substring[index]):
pnext[i] = index + 1
index += 1
i += 1
elif (index!=0):
index = pnext[index-1]
else:
pnext[i] = 0
i += 1
return pnext
def strStr(self, haystack: str, needle: str) -> int:
pnext = self.gen_pnext(needle)
n = len(haystack)
m = len(needle)
i, j = 0, 0
while (i<n) and (j<m):
if (haystack[i]==needle[j]):
i += 1
j += 1
elif (j!=0):
j = pnext[j-1]
else:
i += 1
if (j == m):
return i-j
else:
return -1
python

浙公网安备 33010602011771号