File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ class TrieNode {
2
+ constructor ( ) {
3
+ this . children = { } ; // ๋ฌธ์ -> TrieNode ๋งคํ
4
+ this . isEnd = false ; // ๋จ์ด์ ๋ ํ์
5
+ }
6
+ }
7
+
8
+ class WordDictionary {
9
+ constructor ( ) {
10
+ this . root = new TrieNode ( ) ;
11
+ }
12
+
13
+ /**
14
+ * ๋จ์ด๋ฅผ ํธ๋ผ์ด์ ์ถ๊ฐ
15
+ * Time Complexity: O(L) // L = word.length
16
+ * Space Complexity: O(L) // ์๋ก์ด ๋
ธ๋ ์ต๋ L๊ฐ ์ถ๊ฐ ๊ฐ๋ฅ
17
+ */
18
+ addWord ( word ) {
19
+ let node = this . root ;
20
+ for ( const char of word ) {
21
+ if ( ! node . children [ char ] ) {
22
+ node . children [ char ] = new TrieNode ( ) ;
23
+ }
24
+ node = node . children [ char ] ;
25
+ }
26
+ node . isEnd = true ;
27
+ }
28
+
29
+ /**
30
+ * ๋จ์ด ๋๋ ํจํด ๊ฒ์
31
+ * Time Complexity: O(26^D * L) // D = '.' ๊ฐ์ (์ต๋ 2), L = word.length
32
+ * Space Complexity: O(L) // DFS ์ฌ๊ท ํธ์ถ ์คํ ๊น์ด
33
+ */
34
+ search ( word ) {
35
+ const dfs = ( index , node ) => {
36
+ for ( let i = index ; i < word . length ; i ++ ) {
37
+ const char = word [ i ] ;
38
+ if ( char === '.' ) {
39
+ for ( const child of Object . values ( node . children ) ) {
40
+ if ( dfs ( i + 1 , child ) ) return true ;
41
+ }
42
+ return false ;
43
+ } else {
44
+ if ( ! node . children [ char ] ) return false ;
45
+ node = node . children [ char ] ;
46
+ }
47
+ }
48
+ return node . isEnd ;
49
+ } ;
50
+
51
+ return dfs ( 0 , this . root ) ;
52
+ }
53
+ }
You canโt perform that action at this time.
0 commit comments