Word Break

题目139:Word Break

题目描述:
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

For example, given
s = “leetcode”,
dict = [“leet”, “code”].

Return true because “leetcode” can be segmented as “leet code”.
思路分析:
动态规划,假设res[i]表示长度为i的string能否被切分,也可以理解为下标i以前的字符串能否被切分。动态规划思想,假设现在已经知道res[0]、res[1]……res[i-2]、res[i-1],那如何能求出res[i]。
以res[i-1]为例说明,假设res[i-1]是真,则string中下标0~i-2可以被切分成都在字典里,不妨设在下标j处刚好可以切分,则将string切分成左右两边,string[0~j]对应的word1和string[j+1~i-1]对应的word2,word1和word2都在字典中,如果string[i]对应的word3刚好也在字典种,则res[i]是真;如果word3不在字典中,则换下一个res[k]。
不知道我讲清楚了没有,最后可以得出的是:
res[i] = res[k] && string.substr(k, i - k)是否在字典中;
注意:求子串时下标是从k开始,因为res[k]表示的是长度为k的字符串,下标刚好到k-1。

class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        int len = s.length();
        if (0 == len)
            return false;
        vector<bool> res(len + 1, false);
        /* 无奈的初始化,切分时如果左边是空,右边是整个字符串时,判断是否可以被切分,需要判断res[0],所以res[0]必须是真,不会影响结果 */
        res[0] = true;
        int i, j;
        for (i = 1; i <= len + 1; i ++) {
            for (j = i - 1; j >= 0; -- j) {
                if (res[j] && wordDict.find(s.substr(j, i - j)) != wordDict.end()) {
                    res[i] = true;
                    break;
                }
            }
        }
        return res[len + 1];
    }
};

参考:
[1] http://www.hihuyue.com/hihuyue/codepractise/leetcode/leetcode144-word-break
[2] http://blog.sina.com.cn/s/blog_eb52001d0102v2hp.html
[3] http://www.cnblogs.com/lautsie/p/3371354.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值