1 KMP
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
class Solution {
public:
char *strStr(char *haystack, char *needle) {
int n=strlen(needle);
if(n==0) return haystack;
//kmp
vector<int> nxt(n+1);///@error: nxt should be sized n+1, not n. to contain the nxt[n]
nxt[0]=-1;nxt[1]=0;
for(int i=0;i<n;i++){
int j=nxt[i];
while(j>=0&&needle[i]!=needle[j]) j=nxt[j]; //i matched j
nxt[i+1]=j+1;/@@@@@@@error: nxt[i+1]=j+1; mistake as needle[i+1]=j+1; an Array_Variable_Fault !!!!
}
int j=0;
for(int i=0;haystack[i]!=0;i++,j++){
while(j>=0&&haystack[i]!=needle[j]) j=nxt[j];//i matched j
if(j==n-1) return haystack+i-j; //matche needle
}
return NULL;
}
};
正则匹配不同于一般匹配。回溯取决于*号出现的位置。
采用贪心法:p中'*'尽量匹配s中最少的字符,从上