-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path211.java
64 lines (55 loc) · 1.3 KB
/
211.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.util.HashMap;
import java.util.Map;
class Node {
String val;
Map<Character, Node> dict;
public Node() {
this.val = null;
this.dict = new HashMap<>();
}
public Node(String val) {
this.val = val;
this.dict = new HashMap<>();
}
}
class WordDictionary {
Node head;
public WordDictionary() {
head = new Node();
}
public void addWord(String word) {
Node cur = head;
for (int i = 0; i < word.length(); i++) {
if (cur.dict.containsKey(word.charAt(i))) {
cur = cur.dict.get(word.charAt(i));
} else {
Node next = new Node();
cur.dict.put(word.charAt(i), next);
cur = next;
}
}
cur.val = word;
}
public boolean search(String word) {
return search(word, 0, head);
}
public boolean search(String substring, int i, Node root) {
if (substring.length() == i) {
return root.val != null;
}
if (substring.charAt(i) == '.') {
for (Character c : root.dict.keySet()) {
if (search(substring, i + 1, root.dict.get(c))) {
return true;
}
}
return false;
} else {
if (!root.dict.containsKey(substring.charAt(i))) {
return false;
} else {
return search(substring, i + 1, root.dict.get(substring.charAt(i)));
}
}
}
}