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

矫情吗;* 2024-02-18 22:33 129阅读 0赞

题目描述:

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

若无答案,则返回空字符串。

示例 1:

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

示例 2:

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

注意:

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

解题思路:

暴力法,这个方法时间复杂度O(n^2)

1、遍历找出 (该单词是由words词典中其他单词逐步添加一个字母组成)符合这个条件的单词

并放入数组中

2、找出数组中最长的单词(当长度一样时找出 序数小的单词)

方法二:更为简单,但更灵活,直接遍历

  1. class Solution:
  2. def longestWord(self, words):
  3. """
  4. :type words: List[str]
  5. :rtype: str
  6. """
  7. res = [] #存放符合条件的单词()子单词都在
  8. if (len(words) == 0):
  9. return ''
  10. # list_words = sorted(words)
  11. # 暴力解法
  12. for word in words:
  13. new_word = word
  14. while new_word in words:
  15. new_word = new_word[:-1]
  16. if not new_word:
  17. res.append(word)
  18. #筛选出长度最长(序数最小的词)
  19. result = ''
  20. for key in res:
  21. if len(key)> len(result) or len(key) == len(result) and key < result:
  22. result = key
  23. return result
  24. def longestWord2(self, words):
  25. wordSet = set(words)
  26. result = ''
  27. for word in wordSet:
  28. if(len(word)>len(result) or len(word) == len(result) and word<result):
  29. if all(word[:k] in wordSet for k in range(1,len(word))) :
  30. result = word
  31. return result
  32. if __name__ == '__main__':
  33. words = ["w","wo","wor","worl", "world","worldss",'worlds']
  34. print(Solution().longestWord(words))

发表评论

表情:
评论列表 (有 0 条评论,129人围观)

还没有评论,来说两句吧...

相关阅读