using namespace std; const int LEN=1000005; int next[LEN]; char s[LEN]; char sub[LEN]; void getnext(char sub[],int next[],int len2) { int i=0,j=-1; next[0]=-1; while(i<len2) { if (j==-1||sub[i]==sub[j]) i++,j++,next[i]=j; else j=next[j]; } } int kmp(char s[],char sub[],int len1,int len2,int next[]) { int i=0,j=0; while(i<len1&&j<len2) { if (j==-1||s[i]==sub[j]) i++,j++; else j=next[j]; } if (j>=len2) return i-len2; else return -1; } int main(){ while(cin>>s>>sub){ getnext(sub,next,strlen(sub)); int str=kmp(s,sub,strlen(s),strlen(sub),next);int pre=0; while(pre+str+strlen(sub)<=strlen(s)){ cout<<"match position : "<<pre+str<<endl; for(int i=str+pre;i<str+pre+strlen(sub);i++) printf("%c",s[i]); puts(""); //已经匹配到父串的末尾了 if(pre+str+strlen(sub)==strlen(s))break; //更新已匹配过的长度 pre=pre+str+1; cout<<"pre = "<<pre<<endl; //查找下一个匹配点 str=kmp(s+pre,sub,strlen(s)-pre,strlen(sub),next); if(str==-1)break; system("pause"); } cout<<"new example"<<endl; } }
|