![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/7fcc5df3354742bd88dad28219f82bf8.png
用例:
输入: 0
6
word
dd
da
dc
dword
d
输出: worddwordda
说明: 先确定起始单词word,再接以d开有的且长度最长的单词dword,剩余以d开头且长度最长的有dd、da、dc,则取字典序最小的da,所以最后输出worddwordda
输入: 4
6
word
dd
da
dc
dword
d
输出:dwordda
说明: 先确定起始单词dword,剩余以d开头且长度最长的有dd、da、dc,则取字典序最小的da,所以最后输出dwordda
解法:
const index = 4;
const wordList = ["word", "dd", "da", "dc", "dword", "d"];
function solution(index, wordList) {
let startWord = wordList[index];
let resultStr = startWord;
const filterWords = (startWord, wordList) => {
return wordList
.filter(
(item) =>
item.startsWith(startWord.slice(startWord.length - 1)) &&
item !== startWord
)
.sort()
.sort((a, b) => b.length - a.length);
};
let arry = filterWords(startWord, wordList);
while (true) {
if (arry.length < 1) break;
startWord = arry.shift();
resultStr += startWord;
arry = filterWords(startWord, wordList);
}
return resultStr;
}
console.log(solution(index, wordList));
/* 输入: 0
6
word
dd
da
dc
dword
d
输出: worddwordda */
/* 4
6
word
dd
da
dc
dword
d */