File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ class TrieNode {
2+ constructor ( ) {
3+ this . children = { } ;
4+ this . isEndOfWord = false ;
5+ }
6+ }
7+
8+ var Trie = function ( ) {
9+ this . root = new TrieNode ( ) ;
10+ } ;
11+
12+ /**
13+ * @param {string } word
14+ * @return {void }
15+ */
16+ Trie . prototype . insert = function ( word ) {
17+ let node = this . root ;
18+ for ( const char of word ) {
19+ if ( ! node . children [ char ] ) {
20+ node . children [ char ] = new TrieNode ( ) ;
21+ }
22+ node = node . children [ char ] ;
23+ }
24+ node . isEndOfWord = true ;
25+ } ;
26+
27+ /**
28+ * @param {string } word
29+ * @return {boolean }
30+ */
31+ Trie . prototype . search = function ( word ) {
32+ let node = this . root ;
33+ for ( const char of word ) {
34+ if ( ! node . children [ char ] ) return false ;
35+ node = node . children [ char ] ;
36+ }
37+ return node . isEndOfWord ;
38+ } ;
39+
40+ /**
41+ * @param {string } prefix
42+ * @return {boolean }
43+ */
44+ Trie . prototype . startsWith = function ( prefix ) {
45+ let node = this . root ;
46+ for ( const char of prefix ) {
47+ if ( ! node . children [ char ] ) return false ;
48+ node = node . children [ char ] ;
49+ }
50+ return true ;
51+ } ;
You can’t perform that action at this time.
0 commit comments