模糊匹配
function Node(value) {
this.value = value
this.passCount = 0;
this.endCount = 0;
this.children = {}
}
class WordDictionary {
constructor() {
this.root = new Node(null)
}
addWord(word) {
var node = this.root;
for (var c of word) {
if (!node.children[c]) {
node.children[c] = new Node(c)
}
node = node.children[c]
node.passCount++
}
node.endCount++
}
search(word) {
if (word === '') {
return true
}
return searchRecursively(this.root, word, 0)
}
}
function searchRecursively(cur, word, index) {
if (index == word.length) {
return !!cur.endCount;
}
var c = word.charAt(index);
if (c == '.') {
for (var i in cur.children) { //下一层
if (searchRecursively(cur.children[i], word, index + 1)) {
return true;
}
}
return false;
} else {
var node = cur.children[c]
if (node) {
return searchRecursively(node, word, index + 1);
} else {
return false
}
}
return false
}
leetcode 211. Add and Search Word - Data structure design
原文:https://www.cnblogs.com/rubylouvre/p/12099725.html