File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +42
-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 ch of word ) {
12
+ if ( ! node [ ch ] ) node [ ch ] = { } ;
13
+ node = node [ ch ] ;
14
+ }
15
+ node . isEnd = true ; // ๋จ์ด์ ๋์ ํ์
16
+ } ;
17
+
18
+ /**
19
+ * @param {string } word
20
+ * @return {boolean }
21
+ */
22
+ Trie . prototype . search = function ( word ) {
23
+ let node = this . root ;
24
+ for ( let ch of word ) {
25
+ if ( ! node [ ch ] ) return false ;
26
+ node = node [ ch ] ;
27
+ }
28
+ return node . isEnd === true ; // ๋จ์ด์ ๋์ด์ด์ผ๋ง true
29
+ } ;
30
+
31
+ /**
32
+ * @param {string } prefix
33
+ * @return {boolean }
34
+ */
35
+ Trie . prototype . startsWith = function ( prefix ) {
36
+ let node = this . root ;
37
+ for ( let ch of prefix ) {
38
+ if ( ! node [ ch ] ) return false ;
39
+ node = node [ ch ] ;
40
+ }
41
+ return true ; // ์ ๋์ฌ๋ง ๋งค์นญ๋๋ฉด true
42
+ } ;
You canโt perform that action at this time.
0 commit comments