472. Concatenated Words
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".// Use Dynamic Programming from 139. Word Break
bool helper(string word, unordered_set<string>& dict) {
if (dict.empty()) return false;
int n = word.size();
vector<bool> dp(n + 1, false);
dp[0] = true;
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < i; ++j) {
if (dp[j] && dict.count(word.substr(j, i - j))) {
dp[i] = true;
break;
}
}
}
return dp.back();
}
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
unordered_set<string> dict;
vector<string> res;
sort(words.begin(), words.end(), [](string& w1, string& w2) {
return w1.length() < w2.length();
});
for (string word : words) {
if (helper(word, dict)) res.push_back(word);
dict.insert(word);
}
return res;
}Last updated