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.
我这里用了深度搜索,速度有些慢
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
vector<string> result;
if(words.empty()) return result;
auto mycomp = [&](const string& str1, const string& str2){return str1.size() < str2.size();};
sort(words.begin(), words.end(), mycomp);
unordered_set<string> mp;
for(auto& word: words) {
string path = "";
if(wordBreak(word, mp)) result.push_back(word); // We don't need to insert this word, because it can be concatenated from other words.
else mp.insert(word);
}
return result;
}
private:
bool wordBreak(string& s, unordered_set<string>& wordDict) {
if(s.empty() || wordDict.empty()) return false;
vector<bool> dp(s.size()+1, false);
dp[0] = true;
for(int i = 1; i <= s.size(); i++) {
for(int k = i-1; k >= 0; k--) {
if(dp[k] && wordDict.find(s.substr(k, i-k)) != wordDict.end()) {
dp[i] = true;
break;
}
}
}
return dp[s.size()];
}