思路:
根据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);
}
}
本文介绍了一种使用Trie树(字典树)的数据结构来实现单词字典的方法,该字典支持添加单词及搜索包含通配符'.'的单词。通过递归深度优先搜索实现了对带有通配符的字符串进行高效匹配。
1257

被折叠的 条评论
为什么被折叠?



