题目描述
给定一个不含重复单词的列表,编写一个程序,返回给定单词列表中所有的连接词。
连接词的定义为:一个字符串完全是由至少两个给定数组中的单词组成的。
示例:
输入:
["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
输出:
["catsdogcats","dogcatsdog","ratcatdogcat"]
解释:
"catsdogcats"由"cats", "dog" 和 "cats"组成;
"dogcatsdog"由"dog", "cats"和"dog"组成;
"ratcatdogcat"由"rat", "cat", "dog"和"cat"组成。
说明:
给定数组的元素总数不超过 10000。
给定数组中元素的长度总和不超过 600000。
所有输入字符串只包含小写字母。
不需要考虑答案输出的顺序。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/concatenated-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
这题应该是字典树了,其实也可以用哈希set,毕竟STL的哈希还是非常高效的。。。。(懒得写字典树 )
- 对于字符串s,枚举前缀,如果找到一个前缀在set中,递归判断后面部分的串
边界条件就是递归的深度大于0(0是第一次调用),且串s在set中,直接返回true,相反,如果枚举所有的前缀,都无法匹配,返回false
代码
224 ms, 97.47%
42.3 MB, 94.56%
class Solution {
public:
bool dfs(string s, unordered_set<string>& hash, int depth)
{
if(depth>0 && hash.find(s)!=hash.end()) return true;
for(int i=1; i<s.length(); i++)
{
if(hash.find(string(s.begin(), s.begin()+i))!=hash.end())
if(dfs(string(s.begin()+i, s.end()), hash, depth+1)) return true;
}
return false;
}
vector<string> findAllConcatenatedWordsInADict(vector<string>& words)
{
unordered_set<string> hash(words.begin(), words.end()); hash.insert("");
vector<string> ans;
for(int i=0; i<words.size(); i++)
if(dfs(words[i], hash, 0)) ans.push_back(words[i]);
return ans;
}
};