日新计划720. 词典中最长的单词

112 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第27天,点击查看活动详情

一、题目描述:

720. 词典中最长的单词 - 力扣(LeetCode)

给出一个字符串数组 words 组成的一本英语词典。返回 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" 

提示:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 30
  • 所有输入的字符串 words[i] 都只包含小写字母。

二、思路分析:

需要注意几个点:
1)可能有多个满足条件的单词,需要都保存下来
2)可以直接对字符串排序来得到字典序最小的那个
3)记得处理”没有一个单词满足条件“这个边界情况

其它的思路都在注释里了

三、AC 代码:

class Solution:
    def longestWord(self, words: List[str]) -> str:
        tmpList = []
        tmpLen = 0
        # 遍历所有单词
        for word in words:
            success_mark = 1
            # 遍历该单词从左到右的所有子字符串
            for i in range(1, len(word)):
                if word[:i] in words:
                    continue
                else:
                    # 如果找不到则失败
                    success_mark = 0
                    break
            # 如果找到满足条件的单词,只保存长度最大的那个,有同长度就一起保存
            if success_mark == 1:
                if len(word) > tmpLen:
                    tmpList = [word]
                    tmpLen = len(word)
                elif len(word) == tmpLen:
                    tmpList.append(word)
        if len(tmpList) > 0:
            tmpList.sort()
            res = tmpList[0]
        else:
            res = ""
        return(res)

范文参考

Python直男审美的字典树实现,自从手写一次之后就上瘾了呀 - 词典中最长的单词 - 力扣(LeetCode)

C++ hashmap + 前缀判断(笨方法) - 词典中最长的单词 - 力扣(LeetCode)