word break解题报告

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

https://leetcode.com/problems/word-break/

这道题问的是,有没有,不需要求完整的结果,所以用动态规划进行记录。
dp[i]表示0~i-1之间能不能被break。
dp[0]=true
dp[i]=true当且仅当存在k,i-1>=k>=0,dp[k]且i~k可以被break

解法如下:

class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        vector<bool> dp(s.size()+1,false);
        dp[0]=true;
        for(int i=0;i<s.size();i++){
            for(int j=i;j>=0;j--){
                if(dp[j]&&wordDict.count(s.substr(j,i-j+1))!=0){
                    dp[i+1]=true;
                    break;
                }
            }
        }
        return dp[s.size()];
    }
};
Word Break II

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].
A solution is ["cats and dog", "cat sand dog"].

https://leetcode.com/problems/word-break-ii/

这是问具体结果的题,一般这种题要用DFS进行搜索,但是如果只用DFS那么时间复杂度太大,可以根据上一题,用上一题的条件进行剪枝,以减少时间复杂度。

class Solution {
public:
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
        vector<string> res;
        vector<string> subres;
        vector<bool> posible(s.size()+1,false);
        posible[s.size()]=true;
        for(int i=s.size()-1;i>=0;i--){
            for(int j=i;j<s.size();j++){
                if(dict.count(s.substr(i,j-i+1))!=0&&posible[j+1]){
                    posible[i]=true;
                    break;
                }
            }
        }
        findBreak(s,dict,res,subres,0,posible);
        return res;
    }
    void findBreak(string &s,unordered_set<string> &dict,vector<string> &res,vector<string> &subres,int start,vector<bool> &posible){
        if(start==s.size()){
            string temp=subres[0];
            for(int i=1;i<subres.size();i++){
                temp.append(" "+subres[i]);
            }
            res.push_back(temp);
        }
        for(int i=start;i<s.size();i++){
            string piece=s.substr(start,i-start+1);
            if(dict.count(piece)!=0&&posible[i+1]){
                subres.push_back(piece);
                findBreak(s,dict,res,subres,i+1,posible);
                subres.pop_back();
            }
        }
    }
};



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值