File tree Expand file tree Collapse file tree 1 file changed +70
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +70
-0
lines changed Original file line number Diff line number Diff line change 1+ var Node = function ( ) {
2+ this . children = new Map ( ) ;
3+ this . isEnd = false ;
4+ } ;
5+
6+ var Trie = function ( ) {
7+ this . head = new Node ( ) ;
8+ } ;
9+
10+ /**
11+ * @param {string } word
12+ * @return {void }
13+ */
14+ Trie . prototype . insert = function ( word ) {
15+ let current = this . head ;
16+
17+ for ( const chr of word ) {
18+ if ( ! current . children . has ( chr ) ) {
19+ current . children . set ( chr , new Node ( ) ) ;
20+ }
21+
22+ current = current . children . get ( chr ) ;
23+ }
24+
25+ current . isEnd = true ;
26+ } ;
27+
28+ /**
29+ * @param {string } word
30+ * @return {boolean }
31+ */
32+ 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+ }
39+
40+ current = current . children . get ( chr ) ;
41+ }
42+
43+ return current . isEnd ;
44+ } ;
45+
46+ /**
47+ * @param {string } prefix
48+ * @return {boolean }
49+ */
50+ Trie . prototype . startsWith = function ( prefix ) {
51+ let current = this . head ;
52+
53+ for ( const chr of prefix ) {
54+ if ( ! current . children . has ( chr ) ) {
55+ return false ;
56+ }
57+
58+ current = current . children . get ( chr ) ;
59+ }
60+
61+ return true ;
62+ } ;
63+
64+ /**
65+ * Your Trie object will be instantiated and called as such:
66+ * var obj = new Trie()
67+ * obj.insert(word)
68+ * var param_2 = obj.search(word)
69+ * var param_3 = obj.startsWith(prefix)
70+ */
You can’t perform that action at this time.
0 commit comments