kmp
作者:互联网
KMP算法分两步
一:求子字符串(p)的next数组
void getnext(int nextt[],string p) { nextt[0]=-1; for (int i=1;i<p.size();i++) { int j=nextt[i-1]; while ((p[j+1]!=p[i])&&(j!=-1)) j=nextt[j]; if (p[j+1]==p[i]) nextt[i]=j+1; else nextt[i]=-1; } }
样例:
二:与主字符串(t)匹配
int kmp(int nextt[],string p,string t) { getnext(nextt,p); int i=0,j=0; int ans=0; while (i<t.size()) { if (p[j]==t[i]) { i++; j++; if (j==p.size()) { ans++; j=nextt[j-1]+1; } } else if (j==0) i++; else j=nextt[j-1]+1; } return ans; //ans就是要求的答案. }
vjudge例题Oulipo完整代码如下
#include<bits/stdc++.h> using namespace std; int nextt[12345]; void getnext(int nextt[],string p) { nextt[0]=-1; for (int i=1;i<p.size();i++) { int j=nextt[i-1]; while ((p[j+1]!=p[i])&&(j!=-1)) j=nextt[j]; if (p[j+1]==p[i]) nextt[i]=j+1; else nextt[i]=-1; } } int kmp(int nextt[],string p,string t) { getnext(nextt,p); int i=0,j=0; int ans=0; while (i<t.size()) { if (p[j]==t[i]) { i++; j++; if (j==p.size()) { ans++; j=nextt[j-1]+1; } } else if (j==0) i++; else j=nextt[j-1]+1; } return ans; } int main() { std::ios::sync_with_stdio(false);//快输快出最好加上,不容易超时; std::cin.tie(0); std::cout.tie(0); string p,t; int n; cin>>n; while(n--) { cin>>p>>t; cout<<kmp(nextt,p,t)<<endl; } return 0; }
标签:getnext,string,int,void,nextt,kmp 来源: https://www.cnblogs.com/xxj112/p/16201471.html