[LeetCode]Word Break

解题思路:
动态规划问题,DP[i] 表示是否在wordDict中找到一种组合使得 s中 0到 i 的substr被 space-separated.
1,第一眼看到,就觉得一个for循环是不可能完成任务嗒,要两个for, 时间复杂度O(n2)
2,设置两个指针 i (0~len-1), j(i+1~len),每次去substr[ i ~ j ]
3,DP[ j -1 ] 设置为true的 前提是, i = 0(说明substr[0,j]可以在wordDict中直接找到)或者
     DP[i - 1] = true(这说明 i 之前的substr已经被找到,动态规划状态的转移就在这里)
4, 最后DP[ len - 1] 就是问题的答案

class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        int len = s.length();
        vector<bool> DP(len, false);   // DP[i] means that is there a method to match word before s[i]

        for (int i = 0; i < len; ++i){
            for(int j = i+1; j < len+1; ++j){
                string subs = s.substr(i, j-i);
                if (wordDict.find(subs) != wordDict.end()){
                    if ( i == 0 || DP[i-1]){
                        DP[j-1] = true;
                    }
                }
            }
        }
        return DP[len-1];
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值