File tree Expand file tree Collapse file tree 1 file changed +24
-15
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +24
-15
lines changed Original file line number Diff line number Diff line change @@ -7,6 +7,23 @@ var Trie = function () {
7
7
this . head = new Node ( ) ;
8
8
} ;
9
9
10
+ /**
11
+ * @param {string } str
12
+ * @return {TrieNode | null }
13
+ */
14
+ Trie . prototype . _traverse = function ( str ) {
15
+ let current = this . head ;
16
+
17
+ for ( const chr of str ) {
18
+ if ( ! current . children . has ( chr ) ) {
19
+ return null ;
20
+ }
21
+ current = current . children . get ( chr ) ;
22
+ }
23
+
24
+ return current ;
25
+ } ;
26
+
10
27
/**
11
28
* @param {string } word
12
29
* @return {void }
@@ -30,32 +47,24 @@ Trie.prototype.insert = function (word) {
30
47
* @return {boolean }
31
48
*/
32
49
Trie . prototype . search = function ( word ) {
33
- let current = this . head ;
34
-
35
- for ( const chr of word ) {
36
- if ( ! current . children . has ( chr ) ) {
37
- return false ;
38
- }
50
+ const node = this . _traverse ( word ) ;
39
51
40
- current = current . children . get ( chr ) ;
52
+ if ( ! node ) {
53
+ return false ;
41
54
}
42
55
43
- return current . isEnd ;
56
+ return node . isEnd ;
44
57
} ;
45
58
46
59
/**
47
60
* @param {string } prefix
48
61
* @return {boolean }
49
62
*/
50
63
Trie . prototype . startsWith = function ( prefix ) {
51
- let current = this . head ;
64
+ const node = this . _traverse ( prefix ) ;
52
65
53
- for ( const chr of prefix ) {
54
- if ( ! current . children . has ( chr ) ) {
55
- return false ;
56
- }
57
-
58
- current = current . children . get ( chr ) ;
66
+ if ( ! node ) {
67
+ return false ;
59
68
}
60
69
61
70
return true ;
You can’t perform that action at this time.
0 commit comments