字符串匹配算法的案例

假设有且仅有 1 个最大公共子串。比如,输入 a = "13452439", b = "123456"。由于字符串 "345" 同时在 a 和 b 中出现,且是同时出现在 a 和 b 中的最长子串。因此输出 "345"。

func main() {
    a := "123456"
    b := "13452439"
    maxSubStr := ""
    max_len := 0

    for i := 0; i < len(a); i++ {
        for j := 0; j < len(b); j++ {
            if a[i] == b[j] {
                for m, n := i, j; m < len(a) && n < len(b); m, n = m+1, n+1 {
                    if a[m] != b[n] {
                        break
                    }
                    if max_len < m-i+1 {
                        max_len = m - i + 1
                        maxSubStr = a[i : m+1]
                    }
                }
            }
        }
    }
    fmt.Println(maxSubStr)
}

假设要从主串 s = "goodgoogle" 中找到 t = "google" 子串。

func main() {
    s := "goodgoogle"
    t := "google"
    isfind := 0

    for i := 0; i < len(s) - len(t) + 1; i++ {
        if s[i] == t[0] {
            jc := 0
            for j := 0; j < len(t); j++ {
                if s[i + j] != t[j] {
                    break
                }
                jc = j
            }
            if jc == len(t) - 1 {
                isfind = 1
            }
        }
    }
    fmt.Println(isfind)
}
人生就是要不断折腾
原文地址:https://www.cnblogs.com/xiangxiaolin/p/13590560.html