LeetCode 之 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,我这里用的是自顶向下:

结题思路:

1 用一个数组record来记录,这里的record[i]记录的是原始字符串从第i个元素开始到最后,能否用字典里的单词来进行拼接,所以record[0]就是从第0个元素到最后一个元素组成的字符串能否分割,即最后的结果。因为一个字符串能否进行分割有两种情况,true 或 false,但是我用了一个int来表示,主要是因为最开始并不知道这个字符串能否分割,需要对检测情况加一个标志,我这里用-1表示还未检测过,1表示true(即从i开始到最后的字符串可以进行分割)

2 对每一个字符串s,其长度为length,则这个字符串有length种分割可能:前i个元素为一个单词,length-i个元素则利用递归进行判断。前i个元素组成字符串start,如果i到达了字符串的末尾,则表明可以分割,返回true,同时对record[n]赋为1。对后面的length-i个元素,用end字符串代表。

3 如图所示


代码(28ms):

class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {

        vector<int>record(s.length(),-1);
        
        return subWordBreak(s,dict,record,0);
           
    }
    
    bool subWordBreak(string s, unordered_set<string> &dict , vector<int> &record , int n){
        if(record[n]!=-1) return record[n]==1?true:false;
        for(int i = 0;i<s.length();i++){
            string start = s.substr(0,i+1);
            
            //从0到i 的substr在字典里不存在,就continue
            if(dict.find(start) == dict.end() ){
                continue;
            }
            if(i==s.length()-1){
                record[n] = 1;
                return true;
            }
            
            string end = s.substr(i+1);
            //从i+1到最后的substr在字典里不存在,就检测这个end能否进行分割
            if(dict.find(end) != dict.end() ){
                record[n] = 1;
                return true;
            }
            
            if (subWordBreak(end,dict,record,n+i+1)){
                record[n] = 1;
                return true;
            }
        }
        record[n] = 2;
        return false;
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值