Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
public class Solution { public String strStr(String haystack, String needle) { // Start typing your Java solution below // DO NOT write main() function if(needle.length() == 0)return haystack; if(haystack.length() == 0)return null; int i = 0 ; int j = 0 ; while(i<haystack.length()&&j<needle.length()){ if(haystack.charAt(i) == needle.charAt(j)){ i++; j++; if(j== needle.length()){ return haystack.substring(i-j); } } else{ i = i - j + 1; //wrong here , start to compare after not matched character j = 0; } } return null; } }
mistake: when not matching, i will shit to the start match position +1