暴力求解最后超时了,看了题解才知道什么前缀树和词典书。太菜了。
解法:前缀树
定义前缀树节点类,他的成员为一个节点数组和一个boolean变量用来标志是否是某个单词尾。添加单词时,对树进行遍历,每一个树节点都相当于是一个字母,对于单词word,当遍历到字母r时,如果此时节点的数组下标’r’-‘a’为空的话,就新增一个节点。直到到达单词尾,置尾节点的isOver标志位为true,则增加单词完成。
在进行搜索的时候对该树进行遍历即可。如果遇到字符’.’,则对节点数组的每一个元素都需要搜索一遍,如果为true,返回即可。如果所有节点都搜索过不为true,则返回false。
class WordDictionary {
/** Initialize your data structure here. */
//字典树的头部节点
Tree root;
public WordDictionary() {
root = new Tree();
}
public void addWord(String word) {
//防止破坏头部节点,新定义一个head
Tree head = root;
for(char c : word.toCharArray()){
int t = c - 'a';
//当子节点不存在该字符时,新生成一个子节点
if(head.nums[t] == null){
head.nums[t] = new Tree();
}
//指向子节点
head = head.nums[t];
}
//最后的head对应的就是该单词最后的字符,此时结束符为true,表示存在一个以该字符结尾的单词
head.isOver = true;
}
public boolean search(String word) {
Tree head = root;
return dfs(word , 0 , head);
}
public boolean dfs(String word , int index , Tree head){
//当遍历到所查询单词末尾时,刚好该字符为结束符,即查询命中,返回true,否则返回false
if(index == word.length()){
if(head.isOver) return true;
return false;
}
char c = word.charAt(index);
//遇到‘.’进行26个子节点的遍历,子节点不为null则进行递归,命中一次直接返回true
if(c == '.'){
for(int i = 0 ; i < 26 ; i++){
if(head.nums[i] != null){
if(dfs(word , index+1 , head.nums[i])) return true;
}
}
}else{
//定向寻找,当对应子节点为null时直接返回false,否则进行递归
int t = c - 'a';
if(head.nums[t] != null){
if(dfs(word , index+1 , head.nums[t])) return true;
}
}
return false;
}
}
class Tree{
//子节点集合,对应26个英文字母,大小为26
Tree[] nums;
//单词结束符,用来判断截至到该节点的单词是否存在
boolean isOver = false;
public Tree(){
nums = new Tree[26];
}
}