211.添加与搜索单词,数据结构设计
实现addWord(),search()
1.字典树节点类
class TrieNode{
constructor(val = null){
this.val = val;
this.children = new Map();
this.isWord = false;
}
}
2.初始化字典树,并实现添加和搜索
class wordDictonary{
constructor(){
this.root = new TrieNode(null);
}
//添加
addWord(word){
let ws = this.root;
for(let c of word){
if(!ws.children.get(c))
ws.children.set(c, new TrieNode(c));
ws = ws.children.get(c);
}
ws.isWord = true;
};
//搜索,因为有'.',所有存在递归
search(word){
return this.dfs(word,0,this.root);
};
dfs(word,index,node){
if(!node) return false;
if(index===word.length&&node.isWord) return true;
if(word[index]==='.'){
for(let [k,v] of node.children){
if(this.dfs(word,index+1,v))
return true;
}
}
else{
if(!node.children.get(word[index])) return false;
else
return this.dfs(word,index+1,node.children.get(word[index]));
}
return false;
};