1. 程式人生 > >【LeetCode】472. Concatenated Words 解題報告(C++)

【LeetCode】472. Concatenated Words 解題報告(C++)

作者: 負雪明燭
id: fuxuemingzhu
個人部落格: http://fuxuemingzhu.cn/


目錄

題目地址: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. 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.

題目大意

如果有個字串能夠由其他的至少兩個字串拼接構成,那麼這個字串符合要求。問總的有哪些字串符合要求。

解題方法

動態規劃

這個題的解題方法就是139. Word Break,如果不把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;
    }
};

參考資料:http://www.cnblogs.com/grandyang/p/6254527.html

日期

2018 年 12 月 18 日 —— 改革開放40週年