-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLeetcode211.java
55 lines (51 loc) · 1.69 KB
/
Leetcode211.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
public class Leetcode211 {
class WordDictionary {
class TreeNode{
TreeNode[] children;
boolean isWord;
public TreeNode(){
this.children = new TreeNode[26];
this.isWord = false;
}
}
private TreeNode root;
public WordDictionary() {
this.root = new TreeNode();
}
public void addWord(String word) {
TreeNode node = this.root;
for(int i = 0;i < word.length();i++){
int c = word.charAt(i)-'a';
if(node.children[c] == null){
node.children[c] = new TreeNode();
}
node = node.children[c];
}
node.isWord = true;
}
public boolean search(String word) {
return find(word,root,0);
}
private boolean find(String word, TreeNode node, int index){
if(index == word.length())return node.isWord;
if(word.charAt(index) == '.'){
for(TreeNode n:node.children){
if(n != null && find(word,n,index+1) == true){
return true;
}
}
return false;
}else{
int j = word.charAt(index) - 'a';
TreeNode temp = node.children[j];
return temp != null && find(word, temp, index + 1);
}
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/
}