Design a data structure that supports the following two operations:
void addWord(word) bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z
or .
. A .
means it can represent any one letter.
For example:
addWord("bad") addWord("dad") addWord("mad") search("pad") -> false search("bad") -> true search(".ad") -> true search("b..") -> true
class TrieNode {
TrieNode[] children;
boolean hasWord;
public TrieNode() {
children = new TrieNode[26];
hasWord = false;
}
}
public class WordDictionary {
/** Initialize your data structure here. */
TrieNode root;
public WordDictionary() {
root = new TrieNode();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
TrieNode now = root;
for (int i = 0; i < word.length(); i++) {
int c = word.charAt(i) - 'a';
if (now.children[c] == null) {
now.children[c] = new TrieNode();
}
now = now.children[c];
}
now.hasWord = true;
}
/** 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 find(word, 0, root);
}
public boolean find(String word, int index, TrieNode now) {
if (index == word.length()) {
return now.hasWord;
}
char c = word.charAt(index);
if (c == '.') {
for (int i = 0; i < 26; i++) {
if (now.children[i] != null) {
if (find(word, index + 1, now.children[i])) {
return true;
}
}
}
return false;
} else if (now.children[c - 'a'] != null) {
return find(word, index + 1, now.children[c - 'a']);
} else {
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);
*/
题目不难,直接使用trie树就可以很好的解决。