思路:
根据hint应该用trie树,否则肯定超时。
java code:
public class WordDictionary {
class TrieNode {
boolean isLeaf;
TrieNode[] children = new TrieNode[26];
public TrieNode() {
}
}
private TrieNode root = new TrieNode();
// Adds a word into the data structure.
public void addWord(String word) {
TrieNode node = root;
for(char c : word.toCharArray()) {
if(node.children[c - 'a'] == null) {
node.children[c - 'a'] = new TrieNode();
}
node = node.children[c - 'a'];
}
node.isLeaf = true;
}
// Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
private boolean dfs(String word, TrieNode cur) {
if(cur == null) return false;
if(word.length() == 0) return cur.isLeaf;
TrieNode[] children = cur.children;
char c = word.charAt(0);
if(c == '.') {
for(TrieNode child : children) {
if(child != null && dfs(word.substring(1), child)) {
return true;
}
}
return false;
}else if(children[c - 'a'] != null) {
return dfs(word.substring(1), children[c - 'a']);
}else {
return false;
}
}
public boolean search(String word) {
return dfs(word, root);
}
}