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:
- The number of elements of the given array will not exceed 10,000
- The length sum of elements in the given array will not exceed 600,000.
- All the input string will only include lower case letters.
- The returned elements order does not matter.
方法1: recursion
思路:
和word break一样,先取左边确认可查,然后递归拆解右半部分。这里需要在每次查找前把单词本身删掉,也不需要查找单词自身(左右空子串的情况都不用考虑),
class Solution {
public:
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
unordered_set<string> dict(words.begin(), words.end());
vector<string> result;
for (auto word: words) {
dict.erase(dict.find(word));
if (findAllHelper(word, dict)) {
result.push_back(word);
}
dict.insert(word);
}
return result;
}
bool findAllHelper(string s, unordered_set<string> & dict) {
if (dict.count(s)) return true;
for (int i = 1; i < s.size(); i++) {
string left = s.substr(0, i);
string right = s.substr(i);
if (dict.count(left) && findAllHelper(right, dict)) {
return true;
}
}
return false;
}
};