zoukankan      html  css  js  c++  java
  • 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".
    

      [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    添加单词时注意:“长度是1”的往往比“初始为0”包含的case更 如 c ca cat, m, mo, moc, moch, mocha。所以一般还是写“长度是1”

    [思维问题]:

    [一句话思路]:

    单词前缀都一样的,可以用trie树,也可以用hashset,表示曾经出现过

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    所以一般还是写“长度是1”

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    不是想用hashset,而是数组根本就不能很方便地用.contains()判断存在性

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    class Solution {
        public String longestWord(String[] words) {
            //ini: set,res = "", sort
            Set set = new HashSet();
            String res = "";
            Arrays.sort(words);
            
            //cc
            if (words == null) {
                return res;
            }
            
            //for loop : set.add(w), res ?= w
            for (int i = 0; i < words.length; i++) {
                if (words[i].length() == 1 || set.contains(words[i].substring(0, words[i].length() - 1))) {
                    res = (words[i].length() > res.length()) ? words[i] : res;
                    set.add(words[i]);
                }
            }
            
            //return
            return res;
        }
    }
    View Code
  • 相关阅读:
    所有抽样单元都有相等的被选取机会 ,说法错误
    银行存款余额表由谁编制的
    资本公积——资本溢价与资本公积——其他资本公积
    货币单元抽祥
    企业安全生产费用账务的处理
    Tableau代写制作地图可视化和树形图、条形图
    Tableau 代写数据可视化:探索性图形分析新生儿死亡率数据
    R、Python代写、Open Refine采集pdf数据,清理数据和格式化数据
    使用GIS编程代写制作静态地图和处理地理数据
    用R语言编程代写制作交互式图表和地图
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8960788.html
Copyright © 2011-2022 走看看