My easy-to-understand Solution


  • 0
    Z
    public int strStr(String haystack, String needle) {
            int len1 = haystack.length();
            int len2 = needle.length();
            int i = 0;
            int j = 0;
            
            while(i<len1&&j<len2){
                if(haystack.charAt(i)!=needle.charAt(j)){
                    i = i-j+1; // once not equal, i goes back to start + 1
                    j=0;       // j goes back to 0
                }else{
                    i++;
                    j++;
                }
            }
            
            if(j==len2) return i-j; // j==len2 means it is found, then i -j points to the start pointer
            return -1;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.