Implement strStr ().
Returns the index of the first occurrence of needle in haystack, or-1 if needle are not part of haystack.
Subscribe to see which companies asked this question
Implements a substring that determines whether a string is a string. If yes, returns the first occurrence of the substring if it is not returned-1;
This problem suddenly let me think of KMP algorithm, so to learn a bit KMP algorithm. (see article 1)
But KMP is very complex, especially that part of the matching table, so, I think of it.
Then I thought of this method.
Make up each kid string, and then the inventory matches.
classSolution { Public: BOOLIssame (stringSstringt) { if(s==t)return true; Else return false; } intSTRSTR (stringHaystackstringneedle) { intlen1=haystack.length (); intLen2=needle.length (); stringtmp=""; if(LEN2>LEN1)return-1; if(len2==len1) { if(Issame (Haystack,needle))return 0; Else return-1; } for(intI=0; i<=len1-len2;i++) {tmp=""; for(intj=i;j<i+len2;j++) tmp+=Haystack[j]; if(Issame (Tmp,needle))returni; } return-1; }};
Leetcode 28. Implement StrStr ()