zoukankan      html  css  js  c++  java
  • 472. Concatenated Words

    Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words.

    A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.

    Example:

    Input: ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
    
    Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
    
    Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; 
    "dogcatsdog" can be concatenated by "dog", "cats" and "dog";
    "ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".

    Note:

    1. The number of elements of the given array will not exceed 10,000
    2. The length sum of elements in the given array will not exceed 600,000.
    3. All the input string will only include lower case letters.
    4. The returned elements order does not matter.

    Approach #1: C++.

    class Solution {
    public:
        vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
            unordered_set<string> dict;
            vector<string> ans;
            sort(words.begin(), words.end(), [](string &a, string &b) { return a.length() < b.length(); });
            
            for (string word : words) {
                if (judge(word, dict)) 
                    ans.push_back(word);
                dict.insert(word);
            }
            
            return ans;
        }
        
    private:
        bool judge(string &word, unordered_set<string> &dict) {
            if (word.empty()) {
                return false;
            }
            
            int len = word.length();
            vector<bool> dp(len+1, false);
            dp[0] = true;
            
            for (int i = 1; i <= len; ++i) {
                for (int j = 0; j < i; ++j) {
                    if (dp[j] && dict.find(word.substr(j, i-j)) != dict.end()) {
                        dp[i] = true;
                        break;
                    }
                }
            }
            
            return dp[len];
        }
    };
    

      

    Analysis:

    dp[j] : the substring of word.substr(0, j) can be constituted with the word in dict.

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    制作U盘启动安装CentOS Linux系统
    理解lua中 . : self
    LUA 运算笔记
    技能系统的数据结构
    关于数据结构(二)
    关于数据结构(一)
    WLW/OLW 最佳博客写作软件
    提升ReSharper和Visual Studio的性能
    ReSharper导致Visual Studio缓慢?
    ReSharper 全教程
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10127387.html
Copyright © 2011-2022 走看看