前缀树 力扣练习题 1234567891011121314151617181920212223242526272829303132333435363738394041type TrieNode struct { children [26]*TrieNode isEnd bool //是否有以当前节点为结尾的单词} type Trie struct { root *TrieNode } func Constructor() Trie { return Trie{root: &TrieNode{}} } func (t *Trie) Insert(word string) { move := t.root for _, ch := range word { index := ch - 'a' if move.children[index] == nil { move.children[index] = &TrieNode{} } move = move.children[index] } } func (t *Trie) search(word string) *TrieNode { move := t.root for _, ch := range word { index := ch - 'a' if move.children[index] == nil { return nil } move = move.children[index] } return move } func (t *Trie) Search(word string) bool { node := t.search(word) //找到节点不一定就是找到单词,比如之前插入了apple,但是没有插入app,此时就应该返回false return node != nil && node.isEnd } func (t *Trie) StartsWith(prefix string) bool { node := t.search(prefix) return node != nil } 压缩前缀树