const TrieNode = function () {
this.next = {}
this.isEnd = false
}
const WordDictionary = function () {
this.root = new TrieNode()
}
WordDictionary.prototype.addWord = function() {
if (!word.length) return;
let node = this.root;
for (let i = 0; i < word.length; i++) {
if (!node.next[word[i]]) {
node.next[word[i]] = new TrieNode()
}
node = node.next[word[i]]
}
node.isEnd = true
}
WordDictionary.prototype.search = function () {
if (!word.length) return false
return this.dfs(this.root, word)
}
WordDictionary.prototype.dfs = function (root, word) {
const len = word.length;
let node = root;
for (let i = 0; i < len; ++i) {
const ch = word[i]
if (ch === '.') {
const keys = Reflect.ownKeys(node.next);
for (const key of keys) {
const found = this.dfs(node.next[key], word.slice(i + 1))
if (found) return true;
}
return false;
}
if (!node.next[ch]) {
return false
}
node = node.next[ch]
}
return node.isEnd;
}