HDU1686 KMP模板
仍旧是裸的字符串匹配可以拿来熟悉下字符串匹配问题,我是用来熟悉KMP的。
#include<iostream> #include<cstring> #include<cstdio> using namespace std; const int N = 1e6+5; const int M = 1e4+5; char txt[N] , pat[M]; int pf[M]; void CPF() { pf[1] = 0; int k = 0; int len = strlen(pat+1); for (int i=2;i<=len;i++) { while (k && pat[k+1]!=pat[i]) k = pf[k]; if (pat[k+1]==pat[i]) k++; pf[i] = k; } } int KMP() { int k = 0 , ans=0; int lent = strlen(txt+1) , lenp = strlen(pat+1); // cout << lent << " " << lenp << endl; for (int i=1;i<=lent;i++) { while (k && txt[i]!=pat[k+1]) k = pf[k]; if (pat[k+1]==txt[i]) k++; if (k==lenp) { ans++; } } return ans; }