码迷,mamicode.com
首页 > 其他好文 > 详细

Word Break II

时间:2014-12-03 13:49:18      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

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

class Solution {
public:
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
        int len = s.length();
        for(int i=0; i<len; i++){
            vector<int> tmp(len, 0);
            dp.push_back(tmp);
        }
        vector<bool> reach(len, false);
        for(int i=0; i<len; i++){
            if(i>0 && !reach[i-1]) continue;
            for(int j=i; j<len; j++){
                string sub = s.substr(i, j-i+1);
                if(dict.find(sub) != dict.end()) {
                    reach[j] = true;
                    dp[i][j] = 1;
                }
            }
        }
        string str = "";
        if(reach[len-1])
            helper(0, len, str, s);
        return ans;
    }
    
    void helper(int ind, int len, string str, string s){
        if(ind == len) {
            ans.push_back(str.substr(0, str.length()-1));
            return;
        }
        for(int i=ind; i<len; i++){
            if(dp[ind][i] == 1){
                string nstr = str + s.substr(ind, i-ind+1) + " ";
                helper(i+1, len, nstr, s);
            }
        }
    }
    
    vector<vector<int> > dp;
    vector<string> ans;
};

 

Word Break II

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/code-swan/p/4139673.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!