word break解题报告

来源:互联网 发布:怎样备份软件数据 编辑:程序博客网 时间:2024/05/29 13:09

 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
原创粉丝点击