KMP字符串匹配
#include <bits/stdc++.h> using namespace std; const int N=10005; int next1[1005]; void getnext1(string s) { int i=0/*起始下标*/,j=-1;//起始下标-1 next1[0]=-1; while(i<s.length()-1) //next[i]=当前字符前的子串的前缀和后缀有几个字符相等再加上数组的起始下标 { // cout<<i<<" "<<j<<endl; if(j==-1||s[i]==s[j]) { ++i; ++j; next1[i]=j; } else j=next1[j]; } } void getnext2(string s) //改进next数组 { int i=0,j=-1; next1[0]=-1; while(i<s.length()-1) { // cout<<i<<" "<<j<<endl; if(j==-1||s[i]==s[j]) { ++i; ++j; if(s[i]!=s[j]) //如果s[i]==s[next1[i]]->next[i]=next[nextp[i] next1[i]=j; else next1[i]=next1[j]; } else j=next1[j]; } } int kmp(string s1,string s2) { int i=0/*s1的下标初始位置*/,j=0/*s2的下标初始位置*/; while(i<s1.length()&&j<s2.length()) { if(s1[i]==s2[j]||j==-1) { ++i; ++j; } else j=next1[j]; } if(j>s2.length()-1) return i-s2.length(); else return -1; } int main() { string s1,s2; cin>>s1>>s2; getnext1(s2); //for(int i=0;i<s2.length();i++) //cout<<next1[i]<<endl; cout<<kmp(s1,s2)<<endl; }