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
  • 相关阅读:
    二分图的最大匹配-hdu-3729-I'm Telling the Truth
    hdu3308LCIS(线段树,点更新,段查寻,查寻时一定要注意跨越时如何计算)
    小智慧58
    【开源项目】Android 手写记事 App(半成品)
    持续集成之戏说Check-in Dance
    XSS与字符编码的那些事儿
    十大渗透测试演练系统
    Google DNS劫持背后的技术分析
    黑客是怎样绕过WAF之三重防护绕过讲解
    Seay工具分享
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8960788.html
Copyright © 2011-2022 走看看