Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
題意&解題思路
如題,直接用KMP算法解決,代碼如下:
class Solution {
public:
int strStr(string haystack, string needle) {
int l1 = needle.length();
if(l1 == 0)return 0;
int* Next = new int[l1];
Next[0] = 0;
for(int i = 1, l = 0; i < l1;){
if(needle[i] == needle[l])Next[i++] = ++l;
else if(l)l = Next[l - 1];
else Next[i++] = 0;
}
int len = haystack.length();
for(int i = 0, j = 0; i < len;){
if(haystack[i] == needle[j]){
i++;j++;
}
else{
if(j)j = Next[j - 1];
else i++;
}
if(j == l1)return i - j;
}
return -1;
}
};