-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAddandSearchWord.java
More file actions
64 lines (60 loc) · 1.91 KB
/
AddandSearchWord.java
File metadata and controls
64 lines (60 loc) · 1.91 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
61
62
63
64
class TrieNode {
TrieNode[] children;
boolean isWord;
public TrieNode() {
children = new TrieNode[26];
isWord = false;
}
}
public class WordDictionary {
TrieNode root;
public WordDictionary() {
root = new TrieNode();
}
// Adds a word into the data structure.
public void addWord(String word) {
TrieNode cur = root;
for (int i = 0; i < word.length(); ++i) {
int index = word.charAt(i) - 97;
if (cur.children[index] == null) {
cur.children[index] = new TrieNode();
}
cur = cur.children[index];
}
cur.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) {
if (word.length() == 0) {
return true;
}
return search(word, root);
}
private boolean search(String word, TrieNode node) {
char c = word.charAt(0);
if (c == '.') {
for (int i = 0; i < 26; ++i) {
TrieNode cur = node.children[i];
if (cur != null) {
if (word.length() == 1 && cur.isWord) {
return true;
} else if (word.length() > 1 && search(word.substring(1), cur)) {
return true;
}
}
}
return false;
} else {
TrieNode cur = node.children[c - 97];
if (cur == null) {
return false;
}
return word.length() == 1 ? cur.isWord : search(word.substring(1), cur);
}
}
}
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");