1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
|
package main
import ( "fmt" )
type TrieNode struct { children map[rune]*TrieNode isEnd bool }
type Trie struct { root *TrieNode }
func Constructor() Trie { return Trie{ root: &TrieNode{ children: make(map[rune]*TrieNode), }, } }
func (this *Trie) Insert(word string) { node := this.root for _, ch := range word { if _, exists := node.children[ch]; !exists { node.children[ch] = &TrieNode{ children: make(map[rune]*TrieNode), } } node = node.children[ch] } node.isEnd = true }
func (this *Trie) Search(word string) bool { node := this.root for _, ch := range word { if _, exists := node.children[ch]; !exists { return false } node = node.children[ch] } return node.isEnd }
func (this *Trie) StartsWith(prefix string) bool { node := this.root for _, ch := range prefix { if _, exists := node.children[ch]; !exists { return false } node = node.children[ch] } return true }
func main() { testCases := []struct { actions []string params [][]string expected []interface{} }{ { actions: []string{"Trie", "insert", "search", "search", "startsWith", "insert", "search"}, params: [][]string{{}, {"apple"}, {"apple"}, {"app"}, {"app"}, {"app"}, {"app"}}, expected: []interface{}{nil, nil, true, false, true, nil, true}, }, { actions: []string{"Trie", "insert", "search", "startsWith"}, params: [][]string{{}, {"hello"}, {"hello"}, {"he"}}, expected: []interface{}{nil, nil, true, true}, }, }
for i, tc := range testCases { trie := Constructor() output := []interface{}{nil}
for j := 1; j < len(tc.actions); j++ { action := tc.actions[j] param := tc.params[j]
switch action { case "insert": trie.Insert(param[0]) output = append(output, nil) case "search": result := trie.Search(param[0]) output = append(output, result) case "startsWith": result := trie.StartsWith(param[0]) output = append(output, result) } }
fmt.Printf("Test Case %d, Input: \n", i+1) fmt.Printf("actions = %v\n", tc.actions) fmt.Printf("params = %v\n", tc.params) outputStr := fmt.Sprint(output) expectedStr := fmt.Sprint(tc.expected)
if outputStr == expectedStr { fmt.Printf("Test Case %d, Output: %v, PASS\n", i+1, outputStr) } else { fmt.Printf("Test Case %d, Output: %v, FAIL (Expected: %d)\n", i+1, outputStr, expectedStr) } } }
|