Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button to reset your code definition.
class Solution {
public:
int strStr(char *haystack, char *needle) {
if (!haystack || !needle) return -1;
for (int i = 0; ; ++i) {
for (int j = 0; ; ++j) {
if (needle[j] == 0) return i;
if (haystack[i + j] == 0) return -1;
if (haystack[i + j] != needle[j]) break;
}
}
}
};
class Solution {
public:
int strStr(char *S, char *T) {
if(!S||!T)return -1;
if(!*T)return 0;
int Plen = strlen(T);
int *next = new int[Plen+1];
initKMP(T,next,Plen);
int i=0,j = 0;//i for S,j for T
for(i=0;j<Plen&&*(S+i);){
if(S[i]==T[j]){
i++;j++;
}else if(next[j]>=0){
j = next[j];
}else{
i++;
j = 0;
if(!*(S+i+Plen-1))
break;
}
}
if(j>=Plen)return i-Plen;
else return -1;
}
void initKMP(char str[],int next[],int len){
int i=0,j=-1;
next[0] = -1;
while(i<len){
while(j>=0&&str[i]!=str[j])
j = next[j];
i++;
j++;
if(str[j]==str[i])
next[i] = next[j];
else next[i] = j;
}
}
};
浙公网安备 33010602011771号