(1)28. 实现 strStr()
题目描述:
长串中找出字串是否存在,存在返回位置 不存咋返回-1
解题思路:
偷懒解法,得益于python,可以直接使用切片完成匹配操作
科班解法:KMP算法
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
a = len(needle)
b = len(haystack)
if a == 0:
return 0
next = self.getnext(a, needle)
p =- 1
for j in range(b):
while p>=0 and needle[p+1] != haystack[j]:
p = next[p]
if needle[p+1] == haystack[j]:
p += 1
if p == a-1:
return j-a+1
return -1
def getnext(self,a,needle):
next = ['' for i in range(a)]
k =- 1
next[0] = k
for i in range(1, len(needle)):
while (k>-1 and needle[k+1] != needle[i]):
k = next[k]
if needle[k+1] == needle[i]:
k += 1
next[i] = k
return next
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
return haystack.find(needle)