File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ class WordDictionary {
2
+
3
+ private static class Node {
4
+ Node [] next = new Node [26 ];
5
+ boolean isEnd ;
6
+ }
7
+
8
+ private final Node root = new Node ();
9
+
10
+ public WordDictionary () {}
11
+
12
+ public void addWord (String word ) {
13
+ Node cur = root ;
14
+ for (int k = 0 ; k < word .length (); k ++) {
15
+ char ch = word .charAt (k );
16
+ int i = ch - 'a' ;
17
+ if (cur .next [i ] == null ) cur .next [i ] = new Node ();
18
+ cur = cur .next [i ];
19
+ }
20
+ cur .isEnd = true ;
21
+ }
22
+
23
+ public boolean search (String word ) {
24
+ return dfs (word , 0 , root );
25
+ }
26
+
27
+ private boolean dfs (String word , int idx , Node node ) {
28
+ if (node == null ) return false ;
29
+ if (idx == word .length ()) return node .isEnd ;
30
+
31
+ char ch = word .charAt (idx );
32
+ if (ch == '.' ) {
33
+ // 모든 가능 문자로 한 글자 매칭
34
+ for (int c = 0 ; c < 26 ; c ++) {
35
+ if (node .next [c ] != null && dfs (word , idx + 1 , node .next [c ])) {
36
+ return true ;
37
+ }
38
+ }
39
+ return false ;
40
+ } else {
41
+ return dfs (word , idx + 1 , node .next [ch - 'a' ]);
42
+ }
43
+ }
44
+ }
You can’t perform that action at this time.
0 commit comments