go 前綴樹實現

package main

import "fmt"

type Trie struct {
	IsWord   bool
	Children map[rune]*Trie
}

/** Initialize your data structure here. */
func Constructor() Trie {
	return Trie{IsWord: false, Children: make(map[rune]*Trie)}
}

/** Inserts a word into the trie. */
func (this *Trie) Insert(word string) {
	root := this
	for _, item := range word {
		p := item - 'a'
		if root.Children[p] == nil {
			root.Children[p] = &Trie{IsWord: false, Children: make(map[rune]*Trie)}
		}
		root = root.Children[p]
	}
	root.IsWord = true
}

/** Returns if the word is in the trie. */
func (this *Trie) Search(word string) bool {
	root := this

	for _, item := range word {
		p := item - 'a'

		if root.Children[p] == nil {
			return false
		}
		root = root.Children[p]
	}
	return root.IsWord && root != nil
}

/** Returns if there is any word in the trie that starts with the given prefix. */
func (this *Trie) StartsWith(prefix string) bool {

	root := this

	for _, item := range prefix {
		p := item - 'a'

		if root.Children[p] == nil {
			return false
		}
		root = root.Children[p]
	}
	return root != nil
}

/**
 * Your Trie object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Insert(word);
 * param_2 := obj.Search(word);
 * param_3 := obj.StartsWith(prefix);
 */

func main() {
	trie := Constructor()
	trie.Insert("hello")
	trie.Insert("world")

	res := trie.Search("hel")
	fmt.Println(res, trie)
}

複製代碼
相關文章
相關標籤/搜索