题目描述
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
Note:
You may assume that all words are consist of lowercase letters a-z.
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
分析
本题只能用Trie,但是……LeetCode最近加入了一个测试用例,我试了所有网上能找到的代码,都是Time Limit Exceeded!
代码
class TrieNode {
boolean isLeaf;
char c;
HashMap<Character, TrieNode> children = new HashMap<Character, TrieNode>();
// Initialize your data structure here.
public TrieNode() {
}
public TrieNode(char c) {
this.c = c;
}
}
public class WordDictionary {
private TrieNode root;
public WordDictionary() {
root = new TrieNode();
}
// Adds a word into the data structure.
public void addWord(String word) {
HashMap<Character, TrieNode> children = root.children;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
TrieNode t;
if (children.containsKey(c)) {
t = children.get(c);
} else {
t = new TrieNode(c);
children.put(c, t);
}
children = t.children;
if (i == word.length() - 1) {
t.isLeaf = 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 searchNode(word, root);
}
private boolean searchNode(String word, TrieNode t) {
if (t == null) {
return false;
}
if (word.length() == 0) {
return t.isLeaf;
}
HashMap<Character, TrieNode> children = t.children;
char c = word.charAt(0);
if (c == '.') {
for (char key : children.keySet()) {
if (word.length() == 1 && children.get(key).isLeaf) {
return true;
}
if (searchNode(word.substring(1), children.get(key))) {
return true;
}
}
return false;
} else if (!children.containsKey(c)) {
return false;
} else {
return searchNode(word.substring(1), children.get(c));
}
}
}
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");