NC149 kmp算法——找模式串在文本串中出现的次数

268 阅读1分钟

题目链接

找模式串在文本串中出现的次数。在KMP算法基础实现上稍做调整即可。

下面代码已提交通过。

package main

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 计算模板串S在文本串T中出现了多少次
 * @param S string字符串 模板串
 * @param T string字符串 文本串
 * @return int整型
*/
func kmp( S string ,  T string ) int {
    // write code here
    if S == "" {
        return 1
    }
    sl := len(S)
    tl := len(T)
    if sl > tl { // 模式串比文本串长,直接返回
        return 0
    }
    var (
        si int
        ti int
        next = getNextArray(S)
        c int
    )
    for ti < tl {
        if S[si] == T[ti] {
            si++
            ti++
            if si == sl {
                c++
                si = next[si-1] // 继续找
            }
        } else if si == 0 {
            if tl-ti < sl { // 模式串比文本串剩余部分长,无需再找
                break
            }
            ti++
        } else {
            si = next[si-1]
        }
    }
    return c
}

func getNextArray(p string) []int {
    var (
        j int
        i = 1
        l = len(p)
        next = make([]int, l)
    )
    for i < l {
        if p[i] == p[j] {
            j++
            next[i] = j
            i++
        } else if j == 0 {
            next[i] = 0
            i++
        } else {
            j = next[j-1]
        }
    }
    return next
}