记录日常学习与做题
字典树模板题
由于本题存在通配符 故需要对查找再进行递归
思路:额外申请一个空间用于存放通配符’.’
在查找中,若既不匹配字符又不匹配通配符 返回false,当遇到通配符时,对child所有节点递归,若遇到其中一个满足条件 返回true
class WordDictionary {
class Node {
Node[] child;
boolean isleaf;
public Node() {
child = new Node[27];//最后一个用来往'.'
isleaf = false;
}
}
private Node node;
/**
* Initialize your data structure here.
*/
public WordDictionary() {
node = new Node();
}
//字典树插入模板
private void insert(Node node, String word) {
char[] chars = word.toCharArray();
for (int i = 0; i < chars.length; i++) {
int index = chars[i] - 'a';
if (chars[i] == '.') { //如果遇到了通配符'.' 将其置为26
index = 26;
}
if (node.child[index] == null) {
node.child[index] = new Node();
}
if (i == chars.length - 1) {
node.child[index].isleaf = true;
}
node = node.child[index];
}
}
public void addWord(String word) {
insert(this.node, word);
}
public boolean search(String word) {
return find(this.node, word);
}
private boolean find(Node root, String word) {
char[] chars = word.toCharArray();
for (int i = 0; i < chars.length; i++) {
int index = chars[i] - 'a';
//对遇到通配符的情况进行处理
if (chars[i] == '.') {
boolean flag =false;
for (int j = 0; j < 26; j++) {
if(root.child[j]!=null) {
if(find(root.child[j],word.substring(i+1))){//如果遇到'.' 对后方递归 由于可能有多个word匹配 故这里需要对前26个进行循环 如果有一个满足条件便返回true
flag = true;
}
}
}
return flag;
} else {
if (root.child[index] == null&&root.child[26]==null) { //如果既不是通配符也不匹配
return false;
}
else
{
if(root.child[26]!=null) //如果之前是通配符 将root置为通配符
{
root = root.child[26];
}
else
{
root = root.child[index];
}
}
}
}
return root.isleaf; //返回字典树中是否存在该word
}
}