KMP算法 发表于 2020-09-06 | 分类于 ACM题目合计 | 阅读次数: | KMP板子1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859/* * @Author: onlooker * @Date: 2020-03-07 11:28:45 * @LastEditTime: 2020-09-06 10:42:32 * @FilePath: \code\test.cpp */#include<bits/stdc++.h>using namespace std;#define ll long long#define maxn 15int nextt[maxn]={0};void getnext(string b){ nextt[0]=-1; int i=0,j=-1; int m=b.size(); while(i<m){ if(j==-1||b[i]==b[j]){ i++;j++; nextt[i]=j; } else{ j=nextt[j]; } }}int kmp(string a,string b){ int i=0,j=0; int n=a.size(),m=b.size(); while(i<n&&j<m){ if(a[i]==b[j]||j==-1){ i++;j++; } else{ j=nextt[j]; } } if(j==m){ return i-j; } else{ return -1; }}int main(){ string a,b; cin>>a>>b; getnext(b); int ans=-1; ans=kmp(a,b); if(ans!=-1){ cout<<"find from "<<ans<<" to "<<ans+b.size()-1<<endl; } else{ cout<<"not found"<<endl; } return 0;}