File tree Expand file tree Collapse file tree 1 file changed +81
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +81
-0
lines changed Original file line number Diff line number Diff line change 1+ function Node ( ) {
2+ this . value = null ;
3+ this . wordGraph = new Map ( ) ;
4+ }
5+
6+ var Trie = function ( ) {
7+ this . wordGraph = new Map ( ) ;
8+ } ;
9+
10+ /**
11+ * TC: O(W)
12+ * SC: O(W)
13+ * W: word.length
14+ */
15+
16+ /**
17+ * @param {string } word
18+ * @return {void }
19+ */
20+ Trie . prototype . insert = function ( word ) {
21+ let pointer = this ;
22+ for ( const w of word ) {
23+ if ( ! pointer . wordGraph . has ( w ) ) {
24+ pointer . wordGraph . set ( w , new Node ( ) ) ;
25+ }
26+ pointer = pointer . wordGraph . get ( w ) ;
27+ }
28+ pointer . value = word ;
29+ } ;
30+
31+ /**
32+ * TC: O(W)
33+ * SC: O(1)
34+ * W: word.length
35+ */
36+
37+ /**
38+ * @param {string } word
39+ * @return {boolean }
40+ */
41+ Trie . prototype . search = function ( word ) {
42+ let pointer = this ;
43+ for ( const w of word ) {
44+ if ( ! pointer . wordGraph . has ( w ) ) {
45+ return false ;
46+ } else {
47+ pointer = pointer . wordGraph . get ( w ) ;
48+ }
49+ }
50+ return pointer . value === word ;
51+ } ;
52+
53+ /**
54+ * TC: O(P)
55+ * SC: O(1)
56+ * P:prefix.length
57+ */
58+
59+ /**
60+ * @param {string } prefix
61+ * @return {boolean }
62+ */
63+ Trie . prototype . startsWith = function ( prefix ) {
64+ let pointer = this ;
65+ for ( const p of prefix ) {
66+ if ( ! pointer . wordGraph . has ( p ) ) {
67+ return false ;
68+ } else {
69+ pointer = pointer . wordGraph . get ( p ) ;
70+ }
71+ }
72+ return true ;
73+ } ;
74+
75+ /**
76+ * Your Trie object will be instantiated and called as such:
77+ * var obj = new Trie()
78+ * obj.insert(word)
79+ * var param_2 = obj.search(word)
80+ * var param_3 = obj.startsWith(prefix)
81+ */
You can’t perform that action at this time.
0 commit comments