「每日LeetCode」2021年7月31日

本文最后更新于:2023年3月19日 晚上

Lt720. 词典中最长的单词

720. 词典中最长的单词

给出一个字符串数组words组成的一本英语词典。从中找出最长的一个单词,该单词是由words词典中其他单词逐步添加一个字母组成。若其中有多个可行的答案,则返回答案中字典序最小的单词。
若无答案,则返回空字符串。

示例 1:

1
2
3
4
5
输入:
words = ["w","wo","wor","worl", "world"]
输出:"world"
解释:
单词"world"可由"w", "wo", "wor", 和 "worl"添加一个字母组成。

示例 2:

1
2
3
4
5
输入:
words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
输出:"apple"
解释:
"apply""apple"都能由词典中的单词组成。但是"apple"的字典序小于"apply"

提示:

  • 所有输入的字符串都只包含小写字母。
  • words数组长度范围为[1,1000]
  • words[i]的长度范围为[1,30]

思路

按长度排序后,遍历每一个字符判断其拼写路径是否都在集合中存在,是的话更新 res,最后返回即可。

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* @param {string[]} words
* @return {string}
*/
var longestWord = function (words) {
let max = 0;
let res = "";
const set = new Set();
words.sort((a, b) => a.length - b.length);
const isExist = (word) => {
for (let i = 1; i <= word.length; i++) {
const str = word.slice(0, i);
if (!set.has(str)) return false;
}
return true;
};
for (const word of words) {
set.add(word);
if (
(word.length > max || (word.length === max && word < res)) &&
isExist(word)
) {
res = word;
max = word.length;
}
}
return res;
};