export class Solution {
/**
* longestWord
*
* @param words: a list of strings
* @return: the longest word in words that can be built one character at a time by other words in words
*/
longestWord(words) {
// Write your code here
let resultLength = 0
let resultArray = []
const dic = {}
for(const w of words){
dic[w] = w
}
for(let i = 0;i<26;i++){
const c = String.fromCharCode(97+i)
if(!dic[c]) continue
const r = this.recursion(c,0,dic)
if(r.length > resultLength){
resultArray = []
resultLength = r.length
resultArray.push(r)
}else if(r.length == resultLength){
resultArray.push(r)
}
}
if(resultLength == 0) return ''
return resultArray[0]
}
recursion(s,i,dic){
const c = String.fromCharCode(97+i)
if(i == 26) return s
if(dic[s+c]) return this.max(this.recursion(s+c,0,dic),this.recursion(s,++i,dic))
return this.recursion(s,++i,dic)
}
max(a,b){
if(a.length >= b.length) return a
return b
}
}
LintCode 1071 词典中最长的单词(NodeJS)
最新推荐文章于 2024-07-09 23:43:07 发布