Files
leetcode/top-100-liked/54/leetcode_test.go
T
2026-07-02 13:48:46 +08:00

68 lines
1.3 KiB
Go

package top100liked
import (
"fmt"
"testing"
)
// https://leetcode.cn/problems/implement-trie-prefix-tree/?envType=study-plan-v2&envId=top-100-liked
type Node struct {
children [26]*Node
isEnd bool
}
type Trie struct {
root *Node
}
func Constructor() Trie {
return Trie{root: &Node{}}
}
func (this *Trie) Insert(word string) {
cur := this.root
for i := 0; i < len(word); i++ {
idx := word[i] - 'a'
if cur.children[idx] == nil {
cur.children[idx] = &Node{}
}
cur = cur.children[idx]
}
cur.isEnd = true
}
func (this *Trie) Search(word string) bool {
cur := this.root
for i := 0; i < len(word); i++ {
idx := word[i] - 'a'
if cur.children[idx] == nil {
return false
}
cur = cur.children[idx]
}
return cur.isEnd
}
func (this *Trie) StartsWith(prefix string) bool {
cur := this.root
for i := 0; i < len(prefix); i++ {
idx := prefix[i] - 'a'
if cur.children[idx] == nil {
return false
}
cur = cur.children[idx]
}
return true
}
func Test(t *testing.T) {
trie := Constructor()
trie.Insert("apple")
fmt.Println(trie.Search("apple")) // 返回 True
fmt.Println(trie.Search("app")) // 返回 False
fmt.Println(trie.StartsWith("app")) // 返回 True
trie.Insert("app")
fmt.Println(trie.Search("app")) // 返回 True
}