题目描述:
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
意思就是找到匹配字符串开始的位置,kmp算法。
我的代码:
int strStr(char* haystack, char* needle) {
int a = 0;
int b = 0;
int A = strlen(haystack);
int B= strlen(needle);
if(B==0){
return 0;
}
int index = -1;
while(a<A&&b<B){
if(haystack[a] == needle[b]){
if(b == 0){
index = a;
}
a++;
b++;
}
else{
a++;
b = 0;
if(index != -1){
a = index + 1;
index = -1;
}
}
}
if(b == B){
return index;
}
return -1;
}