繁体   English   中英

golang中创建后缀树

[英]Create a suffix tree in golang

我有一个字符串数组,我需要在 Golang 中创建一个后缀树。 Golang 中的 SuffixArray 不能满足我的需要,因为它只接受字节数组(即单个字符串)。 任何人都可以提供实施的指针。 提前致谢。

这是如何使用后缀数组进行自动完成的示例。 操场)。

请注意,我将所有字符串与前缀\\x00连接在一起,该前缀不能首先出现在字符串中。

package main

import (
    "fmt"
    "index/suffixarray"
    "regexp"
    "strings"
)

func main() {
    words := []string{
        "aardvark",
        "happy",
        "hello",
        "hero",
        "he",
        "hotel",
    }
    // use \x00 to start each string
    joinedStrings := "\x00" + strings.Join(words, "\x00")
    sa := suffixarray.New([]byte(joinedStrings))

    // User has typed in "he"
    match, err := regexp.Compile("\x00he[^\x00]*")
    if err != nil {
        panic(err)
    }
    ms := sa.FindAllIndex(match, -1)

    for _, m := range ms {
        start, end := m[0], m[1]
        fmt.Printf("match = %q\n", joinedStrings[start+1:end])
    }
}

印刷

match = "hello"
match = "hero"
match = "he"

你想要的是广义后缀树。 构建此类树的一种简单方法是将不同的结束标记(未在任何字符串中使用的符号)附加到每个字符串,将它们连接起来并为连接的字符串构建一个普通的后缀树。 所以你只需要在字符串集中添加“hello world”并使用:

match, err := regexp.Compile("[^\x00]*wor[^\x00]*")

获取包含“wor”的字符串。 请注意,正确的字符串是joinedStrings[start:end]

我创建了复杂度为 O(n) 的后缀树的实现,其中 n 是字符串的长度: https : //github.com/twelvedata/searchindex

在我关于 Medium https://medium.com/twelve-data/in-memory-text-search-index-for-quotes-on-go-5243adc62c26 的文章中有更多细节

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM