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+ var Trie = function ( ) {
2+ this . root = { } ;
3+ } ;
4+
5+ /**
6+ * @param {string } word
7+ * @return {void }
8+ */
9+ Trie . prototype . insert = function ( word ) {
10+ let node = this . root ;
11+ for ( let char of word ) {
12+ if ( ! node [ char ] ) {
13+ node [ char ] = { } ;
14+ }
15+ node = node [ char ] ;
16+ }
17+ node . isEndOfWord = true ;
18+ } ;
19+
20+ /**
21+ * @param {string } word
22+ * @return {boolean }
23+ */
24+ Trie . prototype . search = function ( word ) {
25+ let node = this . root ;
26+ for ( let char of word ) {
27+ if ( ! node [ char ] ) {
28+ return false ;
29+ }
30+ node = node [ char ] ;
31+ }
32+ return node . isEndOfWord === true ;
33+ } ;
34+
35+ /**
36+ * @param {string } prefix
37+ * @return {boolean }
38+ */
39+ Trie . prototype . startsWith = function ( prefix ) {
40+ let node = this . root ;
41+ for ( let char of prefix ) {
42+ if ( ! node [ char ] ) {
43+ return false ;
44+ }
45+ node = node [ char ] ;
46+ }
47+ return true ;
48+ } ;
49+
50+ // TC: O(n)
51+ // SC: O(n)
You can’t perform that action at this time.
0 commit comments