题目描述:
给出一个字符串数组words
组成的一本英语词典。从中找出最长的一个单词,该单词是由words
词典中其他单词逐步添加一个字母组成。若其中有多个可行的答案,则返回答案中字典序最小的单词。
若无答案,则返回空字符串。
示例 1:
输入: words = ["w","wo","wor","worl", "world"] 输出: "world" 解释: 单词"world"可由"w", "wo", "wor", 和 "worl"添加一个字母组成。
示例 2:
输入: words = ["a", "banana", "app", "appl", "ap", "apply", "apple"] 输出: "apple" 解释: "apply"和"apple"都能由词典中的单词组成。但是"apple"得字典序小于"apply"。
注意:
- 所有输入的字符串都只包含小写字母。
words
数组长度范围为[1,1000]
。words[i]
的长度范围为[1,30]
。
解题思路:
暴力法,这个方法时间复杂度O(n^2)
1、遍历找出 (该单词是由words
词典中其他单词逐步添加一个字母组成)符合这个条件的单词
并放入数组中
2、找出数组中最长的单词(当长度一样时找出 序数小的单词)
方法二:更为简单,但更灵活,直接遍历
class Solution:
def longestWord(self, words):
"""
:type words: List[str]
:rtype: str
"""
res = [] #存放符合条件的单词()子单词都在
if (len(words) == 0):
return ''
# list_words = sorted(words)
# 暴力解法
for word in words:
new_word = word
while new_word in words:
new_word = new_word[:-1]
if not new_word:
res.append(word)
#筛选出长度最长(序数最小的词)
result = ''
for key in res:
if len(key)> len(result) or len(key) == len(result) and key < result:
result = key
return result
def longestWord2(self, words):
wordSet = set(words)
result = ''
for word in wordSet:
if(len(word)>len(result) or len(word) == len(result) and word<result):
if all(word[:k] in wordSet for k in range(1,len(word))) :
result = word
return result
if __name__ == '__main__':
words = ["w","wo","wor","worl", "world","worldss",'worlds']
print(Solution().longestWord(words))