单词拆分-动态规划139-python&c++

没看答案,动态规划-完全背包问题。

from collections import defaultdict

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        '''
        basecase: dp[0]=True表示背包重量为0时不拿物品也符合。
        state: dp[i]表示s[0:i]能否拼接出来。
               i可以理解为背包重量,wordDict中的元素为物品。
        transfer: dp[i]=True的情况为存在物品word,使s[i-len(word):i]==word,
                  并且dp[i-len(word)]==True即拿物品word之前的字符串也能拼接出来,
                  同时满足以上两种情况极为True。
        result: 返回dp[-1]即为字符串s能否拼接出来。
        '''

        n = len(s)
        dp = [True] + [False] * n

        for i in range(1, n+1):
            for word in wordDict:
                if i >= len(word):
                    dp[i] = (dp[i-len(word)] and s[i-len(word):i] == word)

                if dp[i] == True:
                    break
        
        return dp[-1]

c++

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        // state: dp[i]表示s[0-i]的子字符串可以被拼接出来
        // basecase: dp[0]=true
        // transfer: 遍历所有word,提取i往前word长度n的子字符串sub,dp[i]=true条件为sub==word并且dp[i-n]==true
        // result: dp[s]
        int n = s.size();
        vector<bool> dp(n+1, false);
        dp[0] = true;

        int word_len;
        string sub_s;

        for (int i = 1; i <= n; i++) {
            for (auto& word : wordDict) {
                word_len = word.size();
                if (i < word_len) continue;
                sub_s = s.substr(i-word_len, word_len);
                if (sub_s == word && dp[i-word_len]) dp[i] = true;

                if (dp[i]) break;
            }
        }
        
        return dp[n];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值