-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathWordDictionary.java
More file actions
106 lines (76 loc) · 2.4 KB
/
Copy pathWordDictionary.java
File metadata and controls
106 lines (76 loc) · 2.4 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/**
* url : https://leetcode.com/problems/add-and-search-word-data-structure-design/
*/
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
class TrieNode{
Map<Character, TrieNode> children = new HashMap<>();
boolean isWord;
}
class WordDictionary {
TrieNode root;
public WordDictionary() {
root = new TrieNode();
}
public void addWord(String word){
Map<Character, TrieNode> children = root.children;
TrieNode current = null;
for (int i = 0; i < word.length(); i++) {
char key = word.charAt(i);
if (children.containsKey(key)) {
current = children.get(key);
} else{
current = new TrieNode();
children.put(key, current);
}
children = current.children;
if(i == (word.length() - 1)) {
current.isWord = true;
}
}
}
public boolean search(String word) {
return searchNode(word, root, 0);
}
public boolean searchNode(String word,
TrieNode current,
int len) {
boolean res = false;
if (current == null) {
return false;
}
else if (len == word.length()) {
if (current.isWord) {
res = res || true;
}
}
else if (word.charAt(len) == '.') {
for (Map.Entry<Character, TrieNode> entry : current.children.entrySet()) {
res = res || searchNode(word,
entry.getValue(),
len + 1);
}
} else {
if(current.children.containsKey(word.charAt(len))) {
res = res || searchNode(word,
current.children.get(word.charAt(len)),
len + 1);
}
}
return res;
}
public static void main(String[] args) {
WordDictionary obj = new WordDictionary();
obj.addWord("at");
obj.addWord("and");
obj.addWord("an");
obj.addWord("add");
System.out.println(obj.search("a"));
System.out.println(obj.search(".at"));
obj.addWord("bat");
System.out.println(obj.search(".at"));
System.out.println(obj.search("b.t"));
}
}