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()];
}
本文介绍了一种算法,该算法接收一个不含重复元素的单词列表,并返回所有由至少两个更短单词组成的组合词。通过深度搜索的方法实现,尽管效率较低,但能有效找出符合要求的组合词。
1534

被折叠的 条评论
为什么被折叠?



