以下代码是对力扣 28. 找出字符串中第一个匹配项的下标 题的求解
求 next 数组:
void getNext(int *next, string s){
next[0] = 0;
int j = 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;
if(needle.size() > haystack.size())return -1;
int next[needle.size()];
getNext(next, needle);
int j=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-j+1;
}
}
return -1;
}