Word Break II

class Solution {

    vector<string> res;
    vector<string> midRes;

    // whether string s[0][j] is breakable
    vector<bool> flg;
    /*
    Whether string s[i][j] is in dict.
    Only when s[0][[i-1] is breakable and s[i][j] is in dict,
    will s[i][j] be set to true.
    */
    vector<bool> *midFlg;  
                           
    void dfs(const string &s, int idx) {
        if (idx >= 0) {
            for (int j = 0; j <= idx; ++j) {
                if ( midFlg[j][idx - j] ) {
                    midRes.push_back(s.substr(j, idx - j + 1));
                    dfs(s, j - 1);
                    midRes.pop_back();
                }
            }
        } else {
            string str;
            for (int k = midRes.size() - 1; k >= 0; --k) {
                str += midRes[k];
                if (k > 0) {
                    str += " ";
                }
            }
            
            res.push_back(str);
            return;
        }
    }

public:
    /**
     * @param s a string
     * @param wordDict a set of words
     */
    vector<string> wordBreak(string s, unordered_set<string> &wordDict) {

        int len = s.length();
        
        midFlg = new vector<bool>[len];
        
        int i, j;
        
        // i is 0.
        for (j = 0; j < len; ++j) {
            if (wordDict.find(s.substr(0, j + 1)) != wordDict.end() ) {
                midFlg[0].push_back(true);
                flg.push_back(true);
            } else {
                midFlg[0].push_back(false);
                flg.push_back(false);
            }
        }
        
        // i >= 1
        for (i = 1; i < len; ++i) {
            for (j = i; j < len; ++j) {
                if ( flg[i - 1] && (wordDict.find(s.substr(i, j - i + 1)) != wordDict.end()) ) {
                    midFlg[i].push_back(true);
                    flg[j] = true;
                } else {
                    midFlg[i].push_back(false);
                }
            }
        }
        
        dfs(s, len - 1);
        
        delete []midFlg;
        
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值