Skip to content

Commit 0342217

Browse files
committed
feat(0208): Implement Trie (Prefix Tree)
1 parent 8556df4 commit 0342217

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Implement a trie with insert, search, and startsWith methods.
2+
3+
// Example:
4+
5+
// Trie trie = new Trie();
6+
7+
// trie.insert("apple");
8+
// trie.search("apple"); // returns true
9+
// trie.search("app"); // returns false
10+
// trie.startsWith("app"); // returns true
11+
// trie.insert("app");
12+
// trie.search("app"); // returns true
13+
// Note:
14+
15+
// You may assume that all inputs are consist of lowercase letters a-z.
16+
// All inputs are guaranteed to be non-empty strings.
17+
18+
19+
// 1)
20+
// 做完之后看 Discuss,没太明白为啥都是那种复杂的。
21+
class Trie {
22+
constructor () {
23+
this.list = []
24+
}
25+
insert (word) {
26+
this.list.push(word)
27+
}
28+
search (word) {
29+
return this.list.indexOf(word) > -1
30+
}
31+
startsWith (prefix) {
32+
let res = false
33+
this.list.forEach(word => {
34+
if (word.indexOf(prefix) === 0) {
35+
res = true
36+
}
37+
})
38+
return res
39+
}
40+
}
41+
// Runtime: 492 ms, faster than 6.10% of JavaScript online submissions for Implement Trie (Prefix Tree).
42+
// Memory Usage: 47.7 MB, less than 99.88% of JavaScript online submissions for Implement Trie (Prefix Tree).

0 commit comments

Comments
 (0)