File tree 1 file changed +77
-0
lines changed
design-add-and-search-words-data-structure 1 file changed +77
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 1번풀이 O(n × m)
2
+ class WordDictionary1 {
3
+ private words : string [ ] ;
4
+ constructor ( ) {
5
+ this . words = [ ] ;
6
+ }
7
+
8
+ addWord ( word : string ) : void {
9
+ this . words . push ( word ) ;
10
+ }
11
+ search ( word : string ) : boolean {
12
+ return this . words
13
+ . filter ( ( savedWord ) => savedWord . length === word . length )
14
+ . some ( ( savedWord ) => {
15
+ for ( let i = 0 ; i < word . length ; i ++ ) {
16
+ if ( word [ i ] === "." ) continue ;
17
+ if ( word [ i ] !== savedWord [ i ] ) return false ;
18
+ }
19
+ return true ;
20
+ } ) ;
21
+ }
22
+ } ;
23
+
24
+ // 2번풀이 : Trie(트라이) 자료구조
25
+ type TrieNode = {
26
+ children : { [ key : string ] : TrieNode } ;
27
+ isEnd : boolean ;
28
+ } ;
29
+
30
+ class WordDictionary {
31
+ private root : TrieNode ;
32
+ constructor ( ) {
33
+ this . root = {
34
+ children : { } ,
35
+ isEnd : false ,
36
+ } ;
37
+ }
38
+ addWord ( word : string ) : void {
39
+ let node = this . root ;
40
+
41
+ for ( let i = 0 ; i < word . length ; i ++ ) {
42
+ const char = word [ i ] ;
43
+
44
+ if ( ! node . children [ char ] ) {
45
+ node . children [ char ] = {
46
+ children : { } ,
47
+ isEnd : false ,
48
+ } ;
49
+ }
50
+
51
+ node = node . children [ char ] ;
52
+ }
53
+
54
+ node . isEnd = true ;
55
+ }
56
+ search ( word : string ) : boolean {
57
+ const dfs = ( node : TrieNode , index : number ) : boolean => {
58
+ if ( index === word . length ) return node . isEnd ;
59
+
60
+ const char = word [ index ] ;
61
+
62
+ if ( char === "." ) {
63
+ for ( const nextChar in node . children ) {
64
+ if ( dfs ( node . children [ nextChar ] , index + 1 ) ) {
65
+ return true ;
66
+ }
67
+ }
68
+ return false ;
69
+ }
70
+
71
+ if ( ! node . children [ char ] ) return false ;
72
+ return dfs ( node . children [ char ] , index + 1 ) ;
73
+ } ;
74
+
75
+ return dfs ( this . root , 0 ) ;
76
+ }
77
+ } ;
You can’t perform that action at this time.
0 commit comments