abc a 123456 45 abc ddd
YES YES NO
#include <iostream> #include <string> #include <cstdio> #include <cstring> #include <algorithm> #include <stack> using namespace std; void GET_next(string t, int next[]) { int j, k; j=0; k=-1; next[0]=-1; int len=t.size(); while(j<len ) { if(k==-1 || t[j]==t[k] ) { j++; k++; next[j]=k; } else k=next[k]; } } int KMP(string s, string t, int next[] ) { int i, j; i=0; j=0; int len1=s.size(); int len2=t.size(); while(i<len1 && j<len2 ) { if(j==-1 || s[i]==t[j] ) { i++; j++; } else j=next[j]; } if(j==len2 ) cout<<"YES\n"; else cout<<"NO\n"; return 0; } int main() { string s, t; int i, j; int len1, len2; int next[1000]; while(cin>>s) { cin>>t; len1=s.size(); len2=t.size(); GET_next(t, next); KMP(s, t, next); } return 0; }
原文:http://www.cnblogs.com/yspworld/p/4098253.html