-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathDesign Add and Search Words Data Structure.java
48 lines (44 loc) · 1.2 KB
/
Design Add and Search Words Data Structure.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
class WordDictionary {
private class Node{
boolean last;
Node[] sub;
Node(){
last = false;
sub = new Node[26];
}
}
Node root;
public WordDictionary() {
root = new Node();
}
public void addWord(String word) {
Node temp = root;
for(char c : word.toCharArray()){
int index = c-'a';
if(temp.sub[index] == null)
temp.sub[index] = new Node();
temp = temp.sub[index];
}
temp.last = true;
}
public boolean search(String word) {
Node temp = root;
return dfs(temp, word, 0);
}
private boolean dfs(Node node, String word, int i){
if(i == word.length())
return node.last;
int index = word.charAt(i)-'a';
if(word.charAt(i) == '.'){
for(int j = 0; j < 26; j++){
if(node.sub[j] != null)
if(dfs(node.sub[j], word, i+1))
return true;
}
return false;
}
else if(node.sub[index] == null)
return false;
return dfs(node.sub[index], word, i+1);
}
}