KMP算法和暴力搜索的差别在于多了一个next数组。
暴力求解
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
for i in range(0,len(haystack)-len(needle)+1):
flag = True
for j in range(0,len(needle)):
if haystack[i+j] != needle[j]:
flag = False
break
if j==len(needle)-1 and flag == True:
return i
return -1
haystack = "hello"
needle = "ll"
a = Solution().strStr(haystack,needle)
print(a)
KMP算法中最重要的就是next数组,首先我们先说一下next数组的原理。
next数组在创建的时候它只需要看模式串就可以了,就是比如说你要在s串"BBCABCDABABCDABCDABDE"中找一个p串“ABCDABD”。那这个时候我们只需要看p串去创建next数组就可以了。
接下来说明一下next数组的作用是什么,next数组它是指在p中某个元素之前前缀和后缀相同的个数是几个,比如说在ABCDABD中的AB,就是在最后一个D之前有两个元素一样,那在最后一个B之前就有1一个元素是一样的。
接下来说明一下怎么去构建这个数组。
步骤:
1、创建一个跟模式串p一样长的数组。
2、将第一个值赋值为-1,这个赋值为-1的原因是不从第一个数开始比,
3、创建两个指针向量,分别指向主串和模式串,在创建next数组的过程就相当于在模式串里找模式串自己一样,但是不用完整,只是找从头开始的子串。
4、然后去一个一个比,如果两个字符相同就去比下一个,如果两个字符不相同,就把j=next【j】,大家可以好好理解一下这里为什么是这样做,因为要到这一步了说明匹配不上了,然后就在子串里看前缀和当前后缀的关系。
def Cnext(str):
n = [0 for i in range(len(str))]
n[0] = -1
i = 1
j=-1
while(i<len(str)-1):
if j==-1 or str[i] == str[j]: #为什么j的初始值是-1而不是0,因为原字符串不与本身比较
j+=1
i+=1
n[i] = j
else:
j = n[j]
return n
完整代码:
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle == "":
return 0
def Cnext(str):
n = [0 for i in range(len(str))]
n[0] = -1
i = 1
j=-1
while(i<len(str)-1):
if j==-1 or str[i] == str[j]: #为什么j的初始值是-1而不是0,因为原字符串不与本身比较
j+=1
i+=1
n[i] = j
else:
j = n[j]
return n
n = Cnext(needle)
print(n)
i = 1
j = -1
while (i < len(haystack) and j < len(needle)):
if j == -1 or haystack[i] == needle[j]: # 为什么j的初始值是-1而不是0,因为原字符串不与本身比较
j += 1
i += 1
else:
j = n[j]
if j==len(needle):
return i-len(needle)
'''
for i in range(0,len(haystack)-len(needle)):
flag = True
for j in range(0,len(needle)):
if haystack[i+j] != needle[j]:
flag = False
break
if j==len(needle)-1 and flag == True:
return i
'''
return -1