1. 程式人生 > >word break解題報告

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

這道題問的是,有沒有,不需要求完整的結果,所以用動態規劃進行記錄。
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"].

這是問具體結果的題,一般這種題要用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();
            }
        }
    }
};