File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 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).
You can’t perform that action at this time.
0 commit comments