// at least we need to full scan the haystack string once while (hayIndex < haystack.length()) { // iff the first char is the same should we compare the left elements while (hayIndex < haystack.length() && (c1 = haystack.charAt(hayIndex)) != needle.charAt(0) ) { hayIndex++; } // if there is no same first char if(hayIndex == haystack.length()) { return -1; }else{ // else let's compare the two str // first, let's record the hayIndex ans = hayIndex;
// if needleIndex is less than needle.length(), it is not the same word if(needleIndex < needle.length()){ // let's reset hayIndex back to next char in hayStack // and needleIndex to its first char hayIndex = ans + 1; ans = -1; needleIndex = 0; }else{ return ans; }
classSolution { publicintstrStr(String haystack, String needle) { inti=0, j = 0; intnh= haystack.length(); intnn= needle.length(); int[] next = getNext(needle); while ( i < nh) { if (haystack.charAt(i) == needle.charAt(j)) { i++; j++; if ( j == nn){ return i - j; } }else{ if (j > 0) { j = next[j - 1]; }else{ i++; } } }
return -1; }
publicint[] getNext (String str){ char[] pat = str.toCharArray(); // i - > the first element in suffix inti=1; // j-> the first element in the prefix substring intj=0;