#include<iostream> #include<string.h> #include<stdio.h> #include<fstream> using namespace std; int next[10]; void Next(char*T,int n) { int i=1,j=0; next[1]=0; while(i<n) { if(j==0||T[i-1]==T[j-1]) { i++,j++; next[i]=j; } else j=next[j]; } } //S匹配串,l匹配串长度 //T模式串,n模式串长度 bool KMP(char * S,char * T,int l,int n) { int i=1,j=1; while(i<=l&&j<=n) { if(j==0||S[i-1]==T[j-1]) { i++; j++; } else { j=next[j]; } } if(j>n) return true; return false; } int main() { int i=10; while(i--) { char a[1000],b[1000],c[1000]; cin>>a; cin>>b;//a模式串,b匹配串 int n=strlen(a); int l=strlen(b); Next(a,n);//根据模式串T,初始化next数组 for(int i=0;i<10;i++) cout<<next[i]; if(KMP(b,a,l,n)) { cout<<a<<" "<<b<<" "<<"Yes\n"; } else { cout<<a<<" "<<b<<" "<<"No\n"; } } return 0; }
标签:int,next,char,KMP,include,Next,1000 From: https://www.cnblogs.com/weinan030416/p/17084820.html