JavaScript Sunday algorithm solution


  • 0
    R
    /**
     * @param {string} haystack
     * @param {string} needle
     * @return {number}
     */
    var strStr = function(haystack, needle) {
        
        var textLen = haystack.length
        var patternLen = needle.length
        if (textLen < patternLen)
            return -1
        var shift = {} //创建跳转表
        for (i = 0; i < patternLen; i++) {
            shift[needle[i]] = patternLen - i
        }
        var pos = 0
        while (pos <= (textLen - patternLen)) { 
            var i = pos,
                j
            for (j = 0; j < patternLen; j++, i++) {
                if (haystack[i] !== needle[j]) {
                    var c = haystack[pos + patternLen]
                    pos += typeof shift[c] === 'number' ? shift[c] : patternLen + 1
                    break
                }
            }
            if (j === patternLen) {
                return pos
            }
        }
        return -1
        
    };
    

Log in to reply
 

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