LeetCode:472 连接词 dfs + 哈希set

题目描述

给定一个不含重复单词的列表,编写一个程序,返回给定单词列表中所有的连接词。

连接词的定义为:一个字符串完全是由至少两个给定数组中的单词组成的。

示例:
输入: 
["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;
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值