Description:
Implement strStr ().
Returns the index of the first occurrence of needle in haystack, or-1 if needle are not part of haystack.
Code:
vector<int> GetNext (string&t) {size_t n=t.length (); Vector<int>next (n,-1); inti =0, j =-1; while(I < n1 ) { if(j = =-1|| T[i] = =T[j]) { ++i; ++J; Next[i]=J; } ElseJ=Next[j]; } for(inti =0; I < next.size (); ++i) cout<<Next[i]; cout<<Endl; returnnext;}intINDEXKMP (string& T,string&w, vector<int>&next) { inti =0, j =0; intLENGTHT =t.length (); intLENGTHW =w.length (); while(I < lengtht && J <lengthw) { if(j = =-1|| T[i] = = W[j])//continue to compare subsequent characters { ++i; ++J; } ElseJ=Next[j]; } if(J = =lengthw)returnILENGTHW; Else return-1;} intSTRSTR (stringHaystackstringneedle) { if(Needle = ="") return 0; if(Haystack = ="") return-1; Vector<int>Next; Next=GetNext (needle); returnINDEXKMP (Haystack,needle,next); return-1; }
Implement StrStr ()