题目:28. 实现strStr()
链接:https://leetcode-cn.com/problems/implement-strstr/description/
在字符串haystack中寻找子串needle第一次出现的位置,若匹配失败返回-1。
其实就是python字符串的find方法。下面是一个KMP算法:
python:
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
def getNext(str):
length = len(str)
next = [-1 for i in range(length + 1)]
j, k = 0, -1
while j < length:
if k == -1 or str[j] == str[k]:
j, k = j + 1, k + 1
next[j] = k
else:
k = next[k]
return next
def KMP(s, p):
next = getNext(p)
j = k = 0
length = len(s)
while j < length:
if s[j] == p[k] or k == -1:
j += 1
k += 1
else:
k = next[k]
if k == len(p):
return j - k
return -1
return KMP(haystack,needle)
# return (haystack.find(needle))