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
  • 相关阅读:
    USASO Greedy Gift Givers
    Mat 类型用法
    OpenCV错误:Unhandled exception at 0x0133bc63 ....0xC0000005: Access violation reading location 0x00000004.
    C++ seekp 函数文件流跳转功能产生数据覆盖问题解决
    C++中文件名称必须是C风格的char*格式
    char*, char[] ,CString, string的转换
    Visual Stdio 2008 最大内存分配块大小问题: 使用new 分配连续723M内存 出错 std::bad_alloc at memory location 0x0013e0b8
    string类型转化为char*错误: error C2440: '=' : cannot convert from 'const char *' to 'char *'
    Mat 和 IplImage、CvMat格式的互相转换
    指针数组和数组指针
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8960788.html
Copyright © 2011-2022 走看看