[LeetCode] Word BreakII

本文详细介绍了如何使用字典构建有效句子的算法过程,包括动态规划算法的应用及实现步骤,通过实例演示了字符串 'catsanddog' 构造有效句子的方法。

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


直接根据word breakI 的f[][]数组去build结果

class Solution {
public:
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        vector<string> ret;
        if(s.length() == 0) return ret;
        
        int len = s.length();
        int ** f = new int*[len];
        for(int i = 0; i < len; i++) {
            f[i] = new int[len];
            for(int j = 0; j < len; j++) {
                string tmp = s.substr(i,j-i+1);
                if(dict.find(tmp) != dict.end()) f[i][j] = 1;
                else f[i][j] = 0;
            }
        }
        
        for(int i = 0; i < len; i++) {
            for(int j = i; j < len; j++) {
                for(int k = j+1; k < len; k++) {
                    if(f[i][j] == 1 && f[j+1][k] == 1) {
                        f[i][k] = 1;
                    }
                }
            }
        }
        
        vector<string> tmp;
        build(s,f,0,tmp,ret,dict);
        return ret;
    }
    
    void build(string &s, int **f, int start,vector<string> tmp, vector<string> &ret,unordered_set<string> &dict) {
        int len = s.length();
        if(start > len) return ;
        if(start == len) {
            string t = "";
            for(int i = 0; i < tmp.size(); i++) {
                if(i == 0) t += tmp[i];
                else t += " " + tmp[i];
            }
            ret.push_back(t);
            return;
        }
        
        for(int i = start; i < len; i++) {
            string t = s.substr(start,i-start+1);
            if(dict.find(t) != dict.end()) {
                if(i == len-1) {
                    tmp.push_back(t);
                    build(s,f,i+1,tmp,ret,dict);
                    tmp.pop_back();
                }else {
                    if(f[i+1][len-1]) {
                        tmp.push_back(t);
                        build(s,f,i+1,tmp,ret,dict);
                        tmp.pop_back();
                    }
                }
                
            } 
        }
        
        
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值