"""
词典中最长的单词
desc: 给出一系列字符串单词,表示一个英语词典,找到字典中最长的单词,这些单词可以通过
字典中其他单词每次增加一个字母构成。如果有多个可能的答案,则返回字典顺序最小的
那个。如果没有答案,则返回空字符串。
e.g.: (1) input: words = ["w", "wo", "wor", "worl", "world"]
output: "world",单词"world"可以通过"w", "wo", "wor", "worl", "world"每次增加一个字母组成;
(2) input: words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
output: "apple",单词"apply"和"apple"都能够通过字典里的其他单词构成。但是"apple"的字典序比"apply"小。
输入的所有字符串只包含小写字母,words的长度范围是[1,1000],words[i]的长度范围是[1,30]。
"""
__author__ = "WuYangEzra"
__version__ = "v1.0"
def find_longest_word(words: list) -> str:
"""
find the longest word in words
:param words:
:return:
"""
# 将列表排序(字母顺序小、长度长的字符串靠前原则)
words = sorted(words, key=lambda x: (-len(x), x))
for word in words:
# 依次遍历words列表,符合条件则返回,flag是符合条件标识
flag = True
# 如果没缩减一个字母后形成的字符串均在列表中则说明该字符串可由列表中其他字符串拼接而成
_len = len(word)
for i in range(_len - 1):
part_word = word[0: i+1]
if part_word not in words:
# 标识该word不符合条件
flag = False
break
if flag:
# word符合条件,则返回
return word
if __name__ == '__main__':
words_1 = ["w", "wo", "wor", "worl", "world"]
words_2 = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
for words in (words_1, words_2):
longest_word = find_longest_word(words)
print(longest_word)