-
Notifications
You must be signed in to change notification settings - Fork 277
/
Copy pathAddAndSearchWord.java
68 lines (57 loc) · 1.81 KB
/
AddAndSearchWord.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
class WordDictionary {
private class TrieNode {
private TrieNode[] children = null;
boolean isLeaf;
public TrieNode(){
children = new TrieNode[26];
}
}
private TrieNode root;
/** Initialize your data structure here. */
public WordDictionary() {
root = new TrieNode();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
TrieNode it = root;
for(int i=0;i<word.length();i++){
char c = word.charAt(i);
int index = c -'a';
if(it.children[index]==null){
TrieNode newNode = new TrieNode();
it.children[index] = newNode;
}
it = it.children[index];
}
it.isLeaf = 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 searchHelper(word, 0, root);
}
private boolean searchHelper(String word, int sIndex, TrieNode root){
if(word.length()==sIndex){
return root.isLeaf;
}
char c = word.charAt(sIndex);
if(c=='.'){
for(int i=0;i<26;i++){
if(root.children[i]!=null && searchHelper(word, sIndex+1, root.children[i])){
return true;
}
}
} else {
int index = c -'a';
if(root.children[index]!=null && searchHelper(word, sIndex+1, root.children[index])){
return true;
}
}
return false;
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/