判断字串,直接kmp。
int p[1000000];
void getP(char *needle){
p[0] = -1;
int j=-1;
for(int i=1;needle[i]!='\0';i++){
while(j>=0&&needle[j+1]!=needle[i]) j = p[j];
if(needle[j+1] == needle[i])
j++;
p[i] = j;
}
}
class Solution {
public:
char *strStr(char *haystack, char *needle) {
if(haystack == NULL || needle == NULL)
return NULL;
if(!*needle) return haystack;
int j=-1, len=0;
while(needle[len] !='\0'){
len++;
}
getP(needle);
for(int i=0;haystack[i] != '\0';i++){
while(j>=0&&haystack[i] != needle[j+1]) j = p[j];
if(haystack[i] == needle[j+1])
j++;
if(needle[j+1] == '\0'){
return haystack+i-len+1;
}
}
return NULL;
}
};