1 #include <iostream> 2 #include <string> 3 using namespace std; 4 /* P 为模式串,下标从 0 开始 */ 5 void GetNext(string P,int next[]){ 6 int p_len=P.size(); 7 int i=0; // P 的下标 8 int j=-1; 9 next[0]=-1; 10 11 while(i<p_len-1){ 12 if (j == -1 || P[i] == P[j]){ 13 i++; 14 j++; 15 next[i]=j; 16 } 17 else 18 j=next[j]; 19 } 20 } 21 22 /* 在 S 中找到 P 第一次出现的位置 */ 23 int KMP(string S,string P,int next[]){ 24 GetNext(P, next); 25 int i=0; // S 的下标 26 int j=0; // P 的下标 27 int s_len=S.size(); 28 int p_len=P.size(); 29 while (i<s_len&&j<p_len){ 30 if (j==-1||S[i]==P[j]){ // P 的第一个字符不匹配或 S[i] == P[j] 31 i++; 32 j++; 33 } 34 else 35 j=next[j]; // 当前字符匹配失败,进行跳转 36 } 37 38 if (j==p_len) // 匹配成功 39 return i-j; 40 41 return -1; 42 } 43 44 int main(){ 45 int n; 46 int next[10000]={0}; 47 char a[10000],b[10000]; 48 cin>>a; 49 cin>>b; 50 if(KMP(a,b,next)==0){ 51 cout<<"yes\n"; 52 } 53 else cout<<"no\n"; 54 return 0; 55 }