classSolution{public:intstrStr(string haystack, string needle){int flag =0;int i, j;int sizeofh = haystack.length();int sizeofn = needle.length();if(needle ==""){return0;}for(i =0; i < sizeofh; i++){for(j =0; j < sizeofn; j++){if(i + j > sizeofh){break;}if(haystack[i + j]!= needle[j]){break;}}if(j == sizeofn){
flag =1;break;}}if(flag){return i;}elsereturn-1;}};
官方答案
classSolution{publicintstrStr(String haystack, String needle){int L = needle.length(), n = haystack.length();if(L ==0)return0;int pn =0;while(pn < n - L +1){// find the position of the first needle character// in the haystack stringwhile(pn < n - L +1&& haystack.charAt(pn)!= needle.charAt(0))++pn;// compute the max match stringint currLen =0, pL =0;while(pL < L && pn < n && haystack.charAt(pn)== needle.charAt(pL)){++pn;++pL;++currLen;}// if the whole needle string is found,// return its start positionif(currLen == L)return pn - L;// otherwise, backtrack
pn = pn - currLen +1;}return-1;}}
作者:LeetCode
链接:https://leetcode-cn.com/problems/implement-strstr/solution/shi-xian-strstr-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。