刷题日记-720. 词典中最长的单词

98 阅读1分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

一、题目描述

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

给出一个字符串数组 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. 构建hash
  2. 从长倒短每一个单词检查一遍
  3. 符合前缀条件的并且长度最大的字符记录下来
  4. 按字符排序,取第一个

三、AC 代码

class Solution:
    def longestWord(self, words: List[str]) -> str:
        if len(words) > 0:
            # 1 构建hash
            from collections import Counter
            c = Counter(words)
            # print(c)

            result = []
            max_len = 0
            words = sorted(words,key=lambda x:len(x),reverse=True)
            # print(words)
            for w in words:
                print(w)
                w_mark = True
                # 从长倒短每一个单词检查一遍
                for i in range(1,len(w)):
                    if w[:-i] not in c:
                        w_mark = False
                        break
                #  符合前缀条件的并且,长度最大的字符记录下来
                if w_mark:
                    if len(w) >= max_len:
                        max_len = len(w)
                        result.append(w)
                    
            # 按字符排序
            result = sorted(result)
            print(result)
            if len(result) > 0: return result[0]
            return ''
        else:
            return ''

范文参考

递归+哈希表的解决方法 - 词典中最长的单词 - 力扣(LeetCode) (leetcode-cn.com)