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".

【解法】

看到这道题,第一反应就是深搜,暴力解法,代码如下:

bool wordBreak(string s, unordered_set<string> &dict) {
        auto it = dict.find(s);
       if(it != dict.end()){
            return true;
        }
        for(int i = 0; i < s.length(); i++){
            string str1 = s.substr(0,i);
            string str2 = s.substr(i+1,s.length());
            if(wordBreak(str1,dict) && wordBreak(str2,dict))
                return true;
        }
        return false;
    }
提交之后直接超时,然后分析发现其实是可以用dp去解决的,dp最主要的思想是找到重复子问题,推出状态方程,我们看这道题的状态方程,其实跟其他dp算法还是有点区别的,状态方程为f(i) = 存在j 使得f(j) && s[j+1,i]属于dict ,那么可以写出代码:

bool wordBreak(string s,unordered_set<string> &dict){
        vector<bool> f(s.length()+1,false);
        f[0] = true;
        for(int i = 1; i < s.length()+1 ;i ++){
            for (int j = i-1; j >= 0; j--){
                if(f[j] && (dict.find(s.substr(j,i-j))!=dict.end())){//注意substr的用法,substr(pos,len)
                    f[i] = true;
                }
            }
        }
        return f[f.size()-1];
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值