Skip to content

Commit b9be8a4

Browse files
committed
Add Solution.java to problems 0211
1 parent 46d3f9f commit b9be8a4

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
class WordDictionary {
2+
3+
class TrieNode {
4+
private TrieNode[] links;
5+
private boolean end;
6+
7+
public TrieNode() {
8+
this.links = new TrieNode[26];
9+
}
10+
11+
public boolean contains(char c) {
12+
return links[c - 'a'] != null;
13+
}
14+
15+
public void put(char c, TrieNode trieNode) {
16+
links[c - 'a'] = trieNode;
17+
}
18+
19+
public TrieNode get(char c) {
20+
return links[c - 'a'];
21+
}
22+
}
23+
24+
private TrieNode root;
25+
26+
/** Initialize your data structure here. */
27+
public WordDictionary() {
28+
root = new TrieNode();
29+
}
30+
31+
/** Adds a word into the data structure. */
32+
public void addWord(String word) {
33+
TrieNode node = root;
34+
for (int i = 0; i < word.length(); i++) {
35+
char c = word.charAt(i);
36+
if (!node.contains(c)) {
37+
node.put(c, new TrieNode());
38+
}
39+
node = node.get(c);
40+
}
41+
node.end = true;
42+
}
43+
44+
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
45+
public boolean search(String word) {
46+
return searchHelp(word, root);
47+
}
48+
49+
private boolean searchHelp(String word, TrieNode root) {
50+
TrieNode node = root;
51+
for (int i = 0; i < word.length(); i++) {
52+
char c = word.charAt(i);
53+
54+
if ('.' == c) {
55+
for (int j = 0; j < node.links.length; j++) {
56+
if (node.links[j] != null && searchHelp(word.substring(i + 1), node.links[j])) {
57+
return true;
58+
}
59+
}
60+
return false;
61+
}
62+
if (!node.contains(c)) {
63+
return false;
64+
}
65+
node = node.get(c);
66+
}
67+
return node != null && node.end;
68+
}
69+
}

0 commit comments

Comments
 (0)