题目:
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-strstr
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
个人思路:
就是数据结构里学的KMP算法
官方答案推荐:
暴力、KMP、Sunday许多算法,最经典的肯定是KMP
python代码:
class Solution:
def getNext(self,str):
#i为next数组下标,j为前缀与后缀所匹配的长度
i,j,lenStr = 1,0,len(str)
nextArr = [0]*lenStr
while i<lenStr:
#前后字母相同,匹配长度+1
if str[i] == str[j]:
j += 1
nextArr[i] = j
i += 1
else:
if j==0:
nextArr[i] = 0
i += 1
else:
#回退一个字母,再看这时候的前后缀匹配情况
j = nextArr[j-1]
return nextArr
def strStr(self, haystack: str, needle: str) -> int:
if len(needle)==0:return 0
#求next数组,数组存的是needle数组指针要移动的位置
nextArr = self.getNext(needle)
#i为haystack当前索引,j为needle的索引
i,j = 0,0
while i<len(haystack):
if haystack[i] == needle[j]:
i += 1
j += 1
if j == len(needle):
return i-len(needle)
if i<len(haystack) and haystack[i] != needle[j]:
if j!=0:
#j处的字母不等,则回到j-1处对应的next数组值
j = nextArr[j-1]
else:
i += 1
return -1
反思:
写求next数组的方法真心有点难的。。。