使用前缀树, 多个字符串匹配一个模式
function Node() {
this.children = {}
}
class Trie {
constructor() {
this.root = new Node()
}
insert(word) {
var node = this.root;
for (let c of word) {
if (!node.children[c]) {
node.children[c] = new Node
}
node = node.children[c]
}
node.word = word;
}
search(word) {
var hash = {}
innerSearch(this.root, word, 0, true, hash)
return hash;
}
}
function innerSearch(node, word, index, value, hash) {
if (node.word) {
if (index >= word.length) {
hash[node.word] = value;
} else {
hash[node.word] = false
}
}
var a = word[index]
for (let c in node.children) {
if (c === a) { //都是大写或小写,并且字母一样
innerSearch(node.children[c], word, index + 1, value, hash)
} else {
var code = c.charCodeAt(0)
if (code >= 65 && code <= 90) {
innerSearch(node.children[c], word, index, false, hash)
} else {
innerSearch(node.children[c], word, index, value, hash)
}
}
}
return true
}
function camelMatch(queries, pattern) {
let trie = new Trie
for (let word of queries) {
trie.insert(word)
}
let hash = trie.search(pattern)
let ret = []
for (let word of queries) {
ret.push(hash[word])
}
console.log(ret)
return ret;
}
camelMatch(["FooBar", "FooBarTest", "FootBall", "FrameBuffer", "ForceFeedBack"], 'FB')
camelMatch(["FooBar", "FooBarTest", "FootBall", "FrameBuffer", "ForceFeedBack"], 'FoBa')
camelMatch(["FooBar", "FooBarTest", "FootBall", "FrameBuffer", "ForceFeedBack"], 'FBT')