[String]720. Longest Word in Dictionary

题目:720. Longest Word in Dictionary

Given a list of strings words representing an English Dictionary, find the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order.

If there is no answer, return the empty string.
Example 1:

Input: 
words = ["w","wo","wor","worl", "world"]
Output: "world"
Explanation: 
The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".

Example 2:

Input: 
words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
Output: "apple"

Explanation:
Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
Note:

All the strings in the input will only contain lowercase letters.
The length of words will be in the range [1, 1000].
The length of words[i] will be in the range [1, 30].

Solution:
先排序!+HashSet
Runtime: 35 ms

class Solution {
    public String longestWord(String[] words) {
        Arrays.sort(words);//sort first, so don't need to consider the lexicographically order
        HashSet set = new HashSet();
        String output = "";
        for(String word:words){
            if(word.length() == 1 || set.contains(word.substring(0, word.length()-1))){
                set.add(word);
                if(word.length() > output.length()){
                    output = word;
                }
            }
        }
        return output;
        
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,498评论 0 23
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,965评论 0 33
  • 如果我把心态摆正了,在上研究生那我就,觉得生活很幸福了 像今天我早早来了,就有早来的的作用,看见了就知道原来是这样...
    lygly9阅读 197评论 0 0
  • 每天最惬意的事情就是躺在床上,刷刷新闻,看看电视上那群人又干了啥,看看笑话段子,毕竟高手在民间。玩玩小游戏放松...
    神盾局副局长阅读 529评论 0 0
  • 无法再回头 就连那时读书的心情 都无法重温 那时听过的爱着的歌曲 熟悉的调调却引起心痛 回不去的昨天 你已不再向我...
    昨夜的街灯阅读 220评论 0 1

友情链接更多精彩内容