地址:点击打开链接
这道题就是求一个字符串是否是另一个字符串的子字符串,所以第一种方法首先想到的是KMP算法,其次用暴力破解,还有用素数代表字符,然后根据进位来计算相关和的方法,
但是容易发生溢出,所以就需要采用,大数值或者用KMP算法,这里python的数值好像溢出了,所以就采用KMP,看了两天,里面难点是next数组的求法,具体求法参见july的博客
答案:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
if not haystack and needle:
return -1
haystackLength = len(haystack)
next = self.getNextArr(needle)
needleLength = len(needle)
j = 0
k = 0
while j < haystackLength and k < needleLength:
if k == -1 or haystack[j] == needle[k]:
j += 1
k += 1
else:
k = next[k]
if k == needleLength:
return j - k
else:
return -1
def getNextArr(self,s):
arrLength = len(s)
k = -1
j = 0
next = [ i for i in range(arrLength)]
next[0] = -1
while j < arrLength - 1:
if k == -1 or s[k] == s[j]:
k += 1
j += 1
next[j] = k
else:
k = next[k]
return next