int L = needle.length(), n = haystack.length();for(int start =0; start < n - L +1;++start){if(haystack.substring(start, start + L).equals(needle)){return start;}}return-1;
双指针法
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;}
C语言中的strStr() 等同于 java中的indexOf()利用String方法 int L = needle.length(), n = haystack.length(); for (int start = 0; start < n - L + 1; ++start) { if (haystack.substring(start, start + L).equals(needle)) { return start; } }