File tree 1 file changed +59
-0
lines changed
design-add-and-search-words-data-structure
1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ class TrieNode {
2
+ constructor ( value ) {
3
+ this . value = value ;
4
+ this . children = { } ;
5
+ this . end = false ;
6
+ }
7
+ }
8
+
9
+ class WordDictionary {
10
+ constructor ( ) {
11
+ this . root = new TrieNode ( null ) ;
12
+ }
13
+
14
+ /**
15
+ * 시간복잡도: O(w) (w: word.length)
16
+ * 공간복잡도: O(w)
17
+ * @param {string } word
18
+ * @return {void }
19
+ */
20
+ addWord ( word ) {
21
+ let current = this . root ;
22
+
23
+ for ( const char of word ) {
24
+ if ( ! current . children [ char ] ) {
25
+ const child = new TrieNode ( char ) ;
26
+ current . children [ char ] = child ;
27
+ }
28
+ current = current . children [ char ] ;
29
+ }
30
+
31
+ current . end = true ;
32
+ } ;
33
+
34
+ /**
35
+ * 시간복잡도: O(k * w) (k: children의 길이로 최대 26, w: word.length)
36
+ * 공간복잡도: O(w)
37
+ * @param {string } word
38
+ * @return {boolean }
39
+ */
40
+ search ( word ) {
41
+ return this . #search( this . root , word , 0 ) ;
42
+ } ;
43
+
44
+ #search( node , word , idx ) {
45
+ if ( ! node ) return false ;
46
+ if ( idx >= word . length ) return node . end ;
47
+
48
+ if ( word [ idx ] === '.' ) {
49
+ for ( const current of Object . values ( node . children ) ) {
50
+ if ( this . #search( current , word , idx + 1 ) ) {
51
+ return true ;
52
+ }
53
+ }
54
+ return false ;
55
+ } else {
56
+ return this . #search( node . children [ word [ idx ] ] , word , idx + 1 ) ;
57
+ }
58
+ }
59
+ } ;
You can’t perform that action at this time.
0 commit comments