-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathT211_word_dictionary.java
More file actions
60 lines (53 loc) · 1.7 KB
/
T211_word_dictionary.java
File metadata and controls
60 lines (53 loc) · 1.7 KB
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
public class WordDictionary {
static class TrieNode {
final TrieNode[] children = new TrieNode[26];
boolean end = false;
public void addWord(String word, int idx) {
if (idx == word.length()) {
end = true;
return;
}
char c = word.charAt(idx);
if(children[c - 'a'] == null) {
children[c - 'a'] = new TrieNode();
}
children[c - 'a'].addWord(word, idx + 1);
}
public boolean search(String word, int idx) {
if (idx == word.length()) {
return end;
}
char c = word.charAt(idx);
if (c != '.') {
return children[c - 'a'] != null && children[c - 'a'].search(word, idx + 1);
} else {
for (int i = 0; i < 26; i++) {
if (children[i] != null && children[i].search(word, idx + 1)) {
return true;
}
}
return false;
}
}
}
final TrieNode root = new TrieNode();
// Adds a word into the data structure.
public void addWord(String word) {
root.addWord(word, 0);
}
// 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 root.search(word, 0);
}
public static void main(String[] args) {
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
System.out.println(wordDictionary.search("pad"));
System.out.println(wordDictionary.search("bad"));
System.out.println(wordDictionary.search(".ad"));
System.out.println(wordDictionary.search("b.."));
}
}