Leetcode 472 - Concatenated Words(dp)

66 篇文章 0 订阅

题意

给定一个字符串的列表,列表中的一些字符串能够由列表中的另外一些字符串拼接而成(至少两个)。问能够被拼接的字符串有哪些。

思路

其实和wordBreak那道题一样,只不过我们需要遍历一下待拼接的那个字符串。然后剩下的就是wordBreak一样了。

细节

注意我们用unordered_set来判断字符串是否存在的时候要注意去掉自身。

代码

const int maxn = 10005;
int d[maxn];

class Solution {
public:
    unordered_set<string> has;

    int dfs(string s, int i) {
        if (d[i] != -1) return d[i];
        int ans = 0;
        if (s.substr(0, i + 1) != s && has.count(s.substr(0, i+ 1))) ans = 1;
        else {
            for (int j = 0; j < i; j++) {
                if (ans) break;
                if (s.substr(j + 1, i - j) != s && has.count(s.substr(j + 1, i - j))) ans = dfs(s, j);
            }
        }
        return ans;
    }

    vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
        vector<string> ans;
        for (auto x : words) has.insert(x);
        int n = words.size();
        if (n) {
            memset(d, -1, sizeof(d));
            for (int i = 0; i < n; i++) {
                if (words[i].length() && dfs(words[i], words[i].length() - 1)) {
                    ans.push_back(words[i]);
                }
            }
        }
        return ans;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值