1#include <iostream>2#include <string>3#include <vector>4 using namespacestd;5 BOOLMatched (stringSintKinti)6 {7 BOOLresult=true;8 intp=0;9 intq=i;Ten while(p<k) One { A if(s[p]==S[q]) - { -p++;q--; the } - Else - { -result=false; + Break; - } + } A returnresult; at } -vector<int> Find_next (stringp) - { -vector<int>result; -Result.push_back (0); - for(intI=1; I<p.length (); i++) in { - intk=0; to for(k=i;k>0; k--) + { - if(Matched (p,k,i)) the { * Result.push_back (k); $ Break;Panax Notoginseng } - } the if(k==0) +Result.push_back (0); A } the returnresult; + } - intMain () $ { $ strings,p; -Cin>>s>>p; - thevector<int> next_index=Find_next (p); - intindex_s=0, index_p=0;Wuyi intMatched=0; the while(Index_s<s.length () && index_p<p.length ()) - { Wu if(s[index_s]==p[index_p]) - { Aboutindex_s++;index_p++;matched++; $ } - Else if(matched==0) - { -index_s++; A } + Else the { -index_p=matched-next_index[index_p-1]; $matched=index_p-1; the } the } the if(index_p==p.length ()) the { -cout<<index_s-index_p<<Endl; inSystem"Pause"); the return 0; the } About Else the { thecout<<-1<<Endl; theSystem"Pause"); + return 0; - } the}
KMP String Matching algorithm