题目需要设计并完成前缀树 (Prefix Tree) 来实现。前缀树就是节点为单词间隔,边为单词字符构成的树。因为单词都是有顺序的,所以从根节点开始走到一个标记为结尾的节点,就可以根据边顺序生成一个字符串。
代码如下:
var Node = function() {
// store all the children nodes here
this.children = new Map();
// need a flag to specify if this is a end of the word
this.isWord = false;
}
var WordDictionary = function() {
this.root = new Node();
};
/**
* @param {string} word
* @return {void}
*/
WordDictionary.prototype.addWord = function(word) {
let p = this.root;
// iterate through the word
for (let i = 0; i < word.length; i++) {
const char = word[i];
// if current edge is not created before, add it
if (!p.children.get(char)) {
p.children.set(char, new Node());
}
// bump the pointer
p = p.children.get(char);
}
// set the flag
p.isWord = true;
};
/**
* @param {string} word
* @return {boolean}
*/
WordDictionary.prototype.search = function(word) {
const len = word.length;
const dfs = (node, i) => {
// if it reaches the end,
// then the result depend on the flag value
if (i === len) {
return node.isWord;
}
// if it is '.', we need to check all of its children
if (word[i] === '.') {
for (let [char, val] of node.children) {
if (dfs(val, i + 1)) {
return true;
}
}
return false;
}
// if not, then we do a specific check
const curr = word[i];
if (node.children.get(curr)) {
return dfs(node.children.get(curr), i + 1);
}
return false;
}
// start the search
return dfs(this.root, 0);
};