-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDesignWordSearchDataStructure.java
56 lines (47 loc) · 1.31 KB
/
DesignWordSearchDataStructure.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
class TrieNode {
TrieNode[] children;
boolean word;
public TrieNode() {
children = new TrieNode[26];
word = false;
}
}
class WordDictionary {
private TrieNode root;
public WordDictionary() {
root = new TrieNode();
}
public void addWord(String word) {
TrieNode cur = root;
for (char c : word.toCharArray()) {
if (cur.children[c - 'a'] == null) {
cur.children[c - 'a'] = new TrieNode();
}
cur = cur.children[c - 'a'];
}
cur.word = true;
}
public boolean search(String word) {
return dfs(word, 0, root);
}
private boolean dfs(String word, int j, TrieNode root) {
TrieNode cur = root;
for (int i = j; i < word.length(); i++) {
char c = word.charAt(i);
if (c == '.') {
for (TrieNode child : cur.children) {
if (child != null && dfs(word, i + 1, child)) {
return true;
}
}
return false;
} else {
if (cur.children[c - 'a'] == null) {
return false;
}
cur = cur.children[c - 'a'];
}
}
return cur.word;
}
}