JavaScript with Explaination


  • 0
    /**
     * @param {string} haystack
     * @param {string} needle
     * @return {number}
     */
    var strStr = function(haystack, needle) {
        if (needle.length > haystack.length)
            return -1;
        
        if (needle.length == haystack.length && needle == haystack)
            return 0;
        
        // "" will appear in any haystack with 0 index of first occurrence
        if (needle.length === 0)
            return 0;
            
        var first = needle[0];
        
        // eg:   0123456789
        //      "hayneedles"
        //          "needle"
        // iterate haystack from: [0, 4]
        // which is [0, haystack.length - needle.length]
        for (var i = 0; i <= haystack.length - needle.length; i++) {
            if (haystack[i] == first) {
                var pointer = i + 1;
                // compare the substring of haystack with needle
                for (var j = 1; j < needle.length; j++) {
                    if (needle[j] == haystack[pointer])
                        pointer++;
                    else
                        break;
                }
                if (j >= needle.length)
                    return i;
            }
        }
        
        return -1;
    };
    

Log in to reply
 

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