leetcode:Word Break

题目:https://oj.leetcode.com/problems/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".

题目意思是:给定一个字符串和一个字典,判断该字符串能否由一个或者多个字典中的单词组成。

可以用DP的方法解决。

用数组wb[i]保存从0开始到长度为i的子串能否被分割,所以最后的结果返回wb[s.size() - 1]。

首先wb[0] = true.则wb[1]可分割的条件是:wb[0] == true且子串s[0]包含在字典中...wb[i] == true的条件是:存在0 <= j < i,使得从开始长度为j的子串可分割且从j到i的子串存在在字典中...以此类推求出所有的wb[i]...

AC代码:

class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {
        int len = s.size();
        
        //创建数组wb[i]表示从0开始长度为i的子串能否被分割;最后的答案则是wb[len]
        vector<bool> wb(len + 1,false);
        wb[0] = true;
        
        for(int i = 1;i <= s.size();i++){
            for(int j = i - 1;j >= 0;j--){
                //如果从开始长度为j的子串可以分割而且从j到i的子串出现在字典中
                //则从开始长度为i的子串也可以分割
                if(wb[j] && dict.count(s.substr(j,i - j))){
                    wb[i] = true;
                    break;
                }
            }
        }
        return wb[len];
    }
};





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值