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
  • 相关阅读:
    flv网页视频播放
    Select显示多级分类列表
    DateTime获取一个月的第一天和最后一天
    服务器不装Excel读取Excel并转换DataTable
    ScriptX使用
    CheckBoxList 全选(jquery版本)
    div绝对定位针对手机浏览器的区别
    JAVA 基础编程练习题22 【程序 22 递归求阶乘】
    JAVA 基础编程练习题21 【程序 21 求阶乘】
    JAVA 基础编程练习题20 【程序 20 求前 20 项之和】
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8960788.html
Copyright © 2011-2022 走看看