因为目标S中所含的几个模式P之间可能有重叠部分,所以还需要计算所有字符都匹配时的next,这样继续匹配模式P的时候就不用回溯主串指针了。
1 #include <iostream> 2 #include <cstring> 3 using namespace std; 4 int ans=0,i,j,ls,lp,next[10001]; 5 string s,p; 6 int main() 7 { 8 ios::sync_with_stdio(false); 9 //cin>>ls>>lp>>s>>p; 10 cin>>s>>p;ls=s.length();lp=p.length(); 11 i=0,j=-1; 12 next[0]=-1; 13 while(i<lp) 14 if(j<0||p[i]==p[j]) next[++i]=++j;else j=next[j]; 15 i=0,j=0; 16 while (i<ls) 17 { 18 if (j<0||s[i]==p[j]) i++,j++;else j=next[j]; 19 if (j==lp) {ans++;j=next[j];} 20 } 21 cout<<ans<<endl; 22 }