-
Notifications
You must be signed in to change notification settings - Fork 0
/
211. Add and Search Word - Data structure design
61 lines (52 loc) · 1.7 KB
/
211. Add and Search Word - Data structure design
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
/*
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
For example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
*/
public class WordDictionary {
public class TrieNode {
public TrieNode[] children = new TrieNode[26];
public boolean isWord;
}
private TrieNode root = new TrieNode();
// Adds a word into the data structure.
public void addWord(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (node.children[c - 'a'] == null) {
node.children[c - 'a'] = new TrieNode();
}
node = node.children[c - 'a'];
}
node.isWord = true;
}
// Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
public boolean search(String word) {
return match(word.toCharArray(), 0, root);
}
private boolean match(char[] chs, int k, TrieNode node) {
if (k == chs.length) {
return node.isWord;
}
if (chs[k] == '.') {
for (int i = 0; i < node.children.length; i++) {
if (node.children[i] != null && match(chs, k + 1, node.children[i])) {
return true;
}
}
} else {
return node.children[chs[k] - 'a'] != null && match(chs, k + 1, node.children[chs[k] - 'a']);
}
return false;
}
}