-
Notifications
You must be signed in to change notification settings - Fork 2
/
Solution.java
70 lines (57 loc) · 1.94 KB
/
Solution.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
65
66
67
68
69
70
class WordDictionary {
Trie trie;
public WordDictionary() {
trie = new Trie();
}
public void addWord(String word) {
trie.insert(word);
}
public boolean search(String word) {
return trie.search(word);
}
public class Trie {
private final Node root = new Node();
public Trie() {}
public void insert(String elem) {
if (!elem.isEmpty()) {
Node tmp = root;
for (int i = 0; i < elem.length(); i++) {
if (!tmp.children.containsKey(elem.charAt(i))) {
tmp.children.put(elem.charAt(i), new Node());
}
tmp = tmp.children.get(elem.charAt(i));
}
tmp.isEndOfWord = true;
}
}
public boolean search(String elem) {
return search(root, elem);
}
protected boolean search(Node root, String elem) {
if (root != null && root.isEndOfWord && elem.length() == 0) { return true; }
if (elem.length() == 0 && !root.isEndOfWord) {
return false;
}
char c = elem.charAt(0);
if (c == '.') {
Object[] values = root.children.values().toArray();
for (int i = 0; i < values.length; i++) {
if (search((Node) values[i], elem.substring(1, elem.length()))) {
return true;
}
}
} else {
if (root.children.containsKey(c)) {
return search(root.children.get(c), elem.substring(1, elem.length()));
} else {
return false;
}
}
return false;
}
protected static class Node {
boolean isEndOfWord = false;
final HashMap<Character, Node> children = new HashMap<>();
}
}
}