题目地址:https://leetcode.com/problems/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、 Thenumberofelementsofthegivenarraywillnotexceed10,000;
2、 Thelengthsumofelementsinthegivenarraywillnotexceed600,000.;
3、 Alltheinputstringwillonlyincludelowercaseletters.;
4、 Thereturnedelementsorderdoesnotmatter.;

题目大意

如果有个字符串能够由其他的至少两个字符串拼接构成,那么这个字符串符合要求。问总的有哪些字符串符合要求。

解题方法

动态规划

这个题的解题方法就是139. Word Breakopen in new window,如果不把139搞懂的话,这个题是做不出来的。

方法就是对每个字符串进行一次DP,判断这个字符串是不是能用其他的字符串拼接而成。为了加快判断的速度,使用的是字典保存的字符串。

代码如下:

class Solution {
public:
    vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
        if (words.size() <= 2) return {};
        unordered_set<string> wordset(words.begin(), words.end());
        vector<string> res;
        for (string word : words) {
            wordset.erase(word);
            const int N = word.size();
            if (N == 0) continue;
            vector<bool> dp(N + 1, false);
            dp[0] = true;
            for (int i = 0; i <= N; ++i) {
                for (int j = 0; j < i; ++j) {
                    if (dp[j] && wordset.count(word.substr(j, i - j))) {
                        dp[i] = true;
                        break;
                    }
                }
            }
            if (dp.back())
                res.push_back(word);
            wordset.insert(word);
        }
        return res;
    }
};

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

参考资料:http://www.cnblogs.com/grandyang/p/6254527.html

DDKK.COM 弟弟快看-教程,程序员编程资料站,版权归原作者所有

本文经作者:负雪明烛 授权发布,任何组织或个人未经作者授权不得转发