Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 6716705

Browse files
aQuaaQua
aQua
authored and
aQua
committed
208 accepted. 269ms > 129ms
1 parent 14f63c0 commit 6716705

File tree

3 files changed

+84
-0
lines changed

3 files changed

+84
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# [208. Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/)
2+
3+
## 题目
4+
Implement a trie with insert, search, and startsWith methods.
5+
6+
Note:
7+
You may assume that all inputs are consist of lowercase letters a-z.
8+
9+
## 解题思路
10+
11+
见程序注释
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package Problem0208
2+
3+
/**
4+
* Your Trie object will be instantiated and called as such:
5+
* obj := Constructor();
6+
* obj.Insert(word);
7+
* param_2 := obj.Search(word);
8+
* param_3 := obj.StartsWith(prefix);
9+
*/
10+
11+
// Trie 是便于 word 插入与查找的数据结构
12+
type Trie struct {
13+
words []string
14+
}
15+
16+
// Constructor initialize your data structure here.
17+
func Constructor() Trie {
18+
return Trie{}
19+
}
20+
21+
// Insert a word into the trie.
22+
func (t *Trie) Insert(word string) {
23+
t.words = append(t.words, word)
24+
}
25+
26+
// Search returns true if the word is in the trie.
27+
func (t *Trie) Search(word string) bool {
28+
for _, w := range t.words {
29+
if w == word {
30+
return true
31+
}
32+
}
33+
return false
34+
}
35+
36+
// StartsWith returns true if there is any word in the trie that starts with the given prefix.
37+
func (t *Trie) StartsWith(prefix string) bool {
38+
end := len(prefix)
39+
for _, w := range t.words {
40+
if len(w) >= end && w[:end] == prefix {
41+
return true
42+
}
43+
}
44+
return false
45+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package Problem0208
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func Test_Constructor(t *testing.T) {
10+
ast := assert.New(t)
11+
12+
trie := Constructor()
13+
14+
trie.Insert("abc")
15+
// ["abc"]
16+
17+
ast.True(trie.Search("abc"), "Search abc in [abc]")
18+
// ["abc"]
19+
20+
ast.False(trie.Search("abcd"), "Search abcd in [abc]")
21+
// ["abc"]
22+
23+
ast.True(trie.StartsWith("abc"), "Search startWith abc in [abc]")
24+
// ["abc"]
25+
26+
ast.False(trie.StartsWith("bc"), "Search startWith bc in [abc]")
27+
// ["abc"]
28+
}

0 commit comments

Comments
 (0)