题目描述;
设计一个支持以下两种操作的数据结构:
void addWord(word)
bool search(word)
search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。
示例:
addWord(“bad”)
addWord(“dad”)
addWord(“mad”)
search(“pad”) -> false
search(“bad”) -> true
search(".ad") -> true
search(“b…”) -> true
说明:
你可以假设所有单词都是由小写字母 a-z 组成的。
跟上一题一样,使用前缀树
代码:
class Mytree{
boolean isend;
Mytree child[] = new Mytree[26];
}
Mytree tree ;
public WordDictionary() {
tree = new Mytree();
}
public void addWord(String word) {
Mytree node = tree;
for (char tem : word.toCharArray()) {
if(node.child[tem - 'a'] == null){
node.child[tem - 'a'] = new Mytree();
}
node = node.child[tem - 'a'];
}
node.isend = true;
}
public boolean search(String word) {
Mytree node = tree;
return search(word, node, 0);
}
public boolean search(String word,Mytree node,int index) {
if(index == word.length() && node.isend){
return true;
}
if(index == word.length()){
return false;
}
char tem = word.charAt(index);
if(tem == '.'){
for (int i = 0; i < 26; i++) {
if(node.child[i] != null){
if(search(word, node.child[i], index + 1)){
return true;
}
}
}
return false;
}else {
if(node.child[tem - 'a'] == null){
return false;
}else {
return search(word,node.child[tem - 'a'],index + 1);
}
}
}
}