Javascript solution, use stack to define found


  • 0
    R
    /**
     * @param {string} haystack
     * @param {string} needle
     * @return {number}
     */
    var strStr = function(haystack, needle) {
        if (needle.length === 0) {
            return 0;
        }
        
        if (haystack.length === 0) {
            return -1;
        }
        var i = 0, j = 0, found = [];
        haystack = haystack.toLowerCase();
        needle = needle.toLowerCase();
        
        while (i < haystack.length) {
            if (haystack[i] === needle[j]) {
                found.push(i);
                i++;
                j++;   
            } else {
                j = 0;
                if (found.length > 0) {
                    if (found.length > 1) {
                        i = found[1];
                    }
                } else {
                    i++;
                }
                found = [];
            }
            if (j === needle.length) {
                return found[0];
            }
        }
    
        return -1;
    };
    

Log in to reply
 

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