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
  • 相关阅读:
    sqlserver导入cvs文件
    记录搭建redis集群以及使用过程中踩过的坑
    Linux网络管理工具之mtr
    Linux文本处理三剑客之awk学习笔记12:实战演练
    Linux文本处理三剑客之awk学习笔记11:选项、内置变量和内置函数
    Linux文本处理三剑客之awk学习笔记10:函数
    Linux文本处理三剑客之awk学习笔记09:ARGC和ARGV等
    Linux文本处理三剑客之awk学习笔记08:数组
    Linux文本处理三剑客之awk学习笔记06:输出操作
    Linux文本处理三剑客之awk学习笔记05:getline用法详解
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8960788.html
Copyright © 2011-2022 走看看