登录
首页 >  Golang >  Go问答

在Go中寻找最长匹配子串的方法

来源:stackoverflow

时间:2024-02-19 14:06:26 110浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《在Go中寻找最长匹配子串的方法》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

查找最长子字符串匹配的正确方法是什么? 我一直在尝试在 go 中找到与 regexp 包匹配的最长子字符串:https://pkg.go.dev/regexp

特别是字符串中元音的最长连续匹配。 “aeiou”的任意长度或组合。

这是我现在的代码。它会一直工作,直到字符串变得太长而导致恐慌(超过 1000)。我开始搜索最长的子字符串,并在找到匹配项后返回。

s := "chrononhotonthuooaos"
for i := utf8.RuneCountInString(s); i >=0; i-- {
    exp := "[aeiou]{"
    exp += fmt.Sprint(i)
    exp += "}"
    regexStr := regexp.MustCompile(exp)
    longestStr := regexStr.FindStringSubmatch(s)
    if longestStr != nil {
        fmt.Println("longest submatch found:", longestStr)
        return utf8.RuneCountInString(longestStr[0])
    }
}
return 0

正确答案


您感到恐慌的原因是因为您在每次迭代中创建一个新的正则表达式 - 一个 10,000 个字符的字符串?这是 10,000 个已编译的正则表达式,我很确定它们会被缓存。更不用说正则表达式编译的成本很高。

那么为什么要使用正则表达式呢?像这样的东西几乎肯定更快,不会创建任何中间对象,并且以 o(n) 时间和 o(1) 空间复杂度运行。它适用于任何长度的字符串:

https://goplay.tools/snippet/nvZwWeEF8bC

func longest_vowel_run(s string) (string, int, int) {
    slen := len(s)
    bgn := 0
    end := 0
    max := 0
    x := 0
    y := 0

    // while we still have chars left...
    for x < len(s) {

        // find the first vowel
        for x < slen && !vowel[s[x]] {
            x++
        }
        // find the next non-vowel
        for y = x; y < slen && vowel[s[y]]; {
            y++
        }

        // if the current run is longer than the max run, update the max run
        if z := y - x; z > max {
            bgn = x
            end = y
            max = z
        }

        // pick up where we left off
        x = y

    }

    var maxRun string
    if max > 0 {
        maxRun = s[bgn:end]
    }

    return maxRun, bgn, end - 1
}

var vowel = map[byte]bool{
    'a': true, 'A': true,
    'e': true, 'E': true,
    'i': true, 'I': true,
    'o': true, 'O': true,
    'u': true, 'U': true,
}

到这里,我们也就讲完了《在Go中寻找最长匹配子串的方法》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>