Given two strings needle
and haystack
, return the index of the first occurrence of needle
in haystack
, or -1
if needle
is not part of haystack
.
Example 1:
Input: haystack = "sadbutsad", needle = "sad" Output: 0 Explanation: "sad" occurs at index 0 and 6. The first occurrence is at index 0, so we return 0.
Example 2:
Input: haystack = "leetcode", needle = "leeto" Output: -1 Explanation: "leeto" did not occur in "leetcode", so we return -1.
Constraints:
1 <= haystack.length, needle.length <= 104
haystack
andneedle
consist of only lowercase English characters.
class Solution {
public:
void getNext(string &s,int *next){
int j=0;
next[0]=0;
for(int i=1;i<s.size();i++){
while(j>0 && s[i]!=s[j])j=next[j-1];
if(s[i]==s[j])j++;
next[i]=j;
}
}
int strStr(string haystack, string needle) {
if(needle.size()==0)return 0;
int j=0;
vector<int>next(needle.size());
getNext(needle,&next[0]);
for(int i=0;i<haystack.size();i++){
while(j>0 && haystack[i]!=needle[j])j=next[j-1];
if(haystack[i]==needle[j])j++;
if(j==needle.size())return (i-needle.size()+1);
}
return -1;
}
};
注意:
1.前缀表是什么?为什么要这样用——KMP算法
2.Next数组怎么求