import java.util.HashMap;
public class WordDictionary {
private class Node {
public boolean isWord;
public HashMap<Character, Node> next;
public Node(boolean isWord) {
this.isWord = isWord;
next = new HashMap<>();
}
public Node() {
this(false);
}
}
private Node root;
/** Initialize your data structure here. */
public WordDictionary() {
root = new Node();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
addWord(root, word, 0);
}
private void addWord(Node node, String word, int index) {
if (word.length() == index) {
if (!node.isWord) {
node.isWord = true;
}
return;
}
char c = word.charAt(index);
if (node.next.get(c) == null) {
node.next.put(c, new Node());
}
addWord(node.next.get(c), word, index + 1);
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
public boolean search(String word) {
return search(root, word, 0);
}
private boolean search(Node node, String word, int index) {
if (word.length() == index) {
return node.isWord;
}
char c = word.charAt(index);
if (c != '.') {
if (node.next.get(c) == null) {
return false;
}
return search(node.next.get(c), word, index + 1);
} else {
for (Character character : node.next.keySet()) {
if (search(node.next.get(character), word, index + 1)) {
return true;
}
}
return false;
}
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/
网友评论