算法学习记录(二十二)

120 阅读1分钟

问:

  1. KMP算法查找str1中str2第一次出现的位置

解:

  1. 较为复杂,可跳转至www.bilibili.com/video/BV13g… 01:28:00处。左程云老师详解KMP算法流程细节与实现。
function KMP(str1, str2) {
    // str2的最长前后缀信息
    const infoArr = charPreSuffixInfo(str2)
    let idx1 = 0
    let idx2 = 0
    while (idx1 < str1.length && idx2 < str2.length) {
        if (str1[idx1] === str2[idx2]) {
            idx1++
            idx2++
        } else if (idx2 === 0) {
            idx1++
        } else {
            idx2 = infoArr[idx2]
        }
    }
    return idx2 === str2.length ? idx1 - idx2 : -1
    function charPreSuffixInfo(str) {
        if (!str.length) return []
        if (str.length === 1) return [-1]
        if (str.length === 2) return [-1, 0]
        let idx = 2
        const res = [-1, 0]
        let targetIdx = res[idx -1]
        while (idx < str.length) {
            if (str[idx -1] === str[targetIdx]) {
                res[idx++] = ++targetIdx
            } else if (targetIdx <= 0) {
                res[idx++] = 0
            } else {
                targetIdx = res[targetIdx]
            }
        }
        return res
    }
}