使用前缀树
function Node() {
this.word = ''
this.children = {}
}
class Tire {
constructor() {
this.root = new Node()
}
addWord(word) {
var node = this.root;
for (let next of word) {
if (!node.children[next]) {
node.children[next] = new Node()
}
node = node.children[next]
}
node.word = word;
}
search(word) {
var node = this.root;
for (let c of word) {
if (!node.children[c] || !node.children[c].word) {
return false
}
node = node.children[c]
}
return true
}
}
var longestWord = function (words, k) {
if (!words.length) {
return ''
}
var tire = new Tire;
for (let word of words) {
tire.addWord(word)
}
var ret = ''
for (let word of words) {
if (tire.search(word)) {
if (word.length > ret.length) {
ret = word;//更新最长单词
} else if (word.length === ret.length && word.localeCompare(ret) < 0) {
ret = word
}
} else { //过滤掉单词的前缀部分
// console.log("----", word) //不懂
}
}
return ret;
};
console.log(longestWord(["ogz", "eyj", "e", "ey",
"hmn", "v", "hm", "ogznkb", "ogzn", "hmnm",
"eyjuo", "vuq", "ogznk", "og", "eyjuoi", "d"]
))
console.log(longestWord(["w", "wo", "wor", "worl", "world"]))
console.log(longestWord(["a", "banana", "app", "appl", "ap", "apply", "apple"]))
leetcode 720. Longest Word in Dictionary
原文:https://www.cnblogs.com/rubylouvre/p/12113344.html