-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDesignAddSearchWords.java
71 lines (57 loc) · 1.76 KB
/
DesignAddSearchWords.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
69
70
71
package Gem.Trie;
import java.util.HashMap;
import java.util.Map;
class WordDictionary {
private class Node {
private boolean isWord;
private Map<Character, Node> next;
public Node(boolean isWord) {
this.isWord = isWord;
next = new HashMap<>();
}
public Node() {
this(false);
}
}
private Node root;
public WordDictionary() {
this.root = new Node();
}
public void addWord(String word) {
Node curr = root;
for(char c : word.toCharArray()) {
if(!curr.next.containsKey(c))
curr.next.put(c, new Node());
curr = curr.next.get(c);
}
curr.isWord = true;
}
private boolean match(Node node, String word, int index) {
if (index == word.length()) {
return node.isWord;
}
Character currC = word.charAt(index);
if (currC == '.') {
for (Character c : node.next.keySet()) {
if(match(node.next.get(c), word, index + 1)){
return true;
}
}
return false;
} else {// currC!='.'
if (node.next.get(currC) == null) {
return false;
}
return match(node.next.get(currC), word, index + 1);
}
}
public boolean search(String word) {
return match(root, word, 0);
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/