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

题目大意 给定一个单词集合和一个字符串序列,要求根据已有的单词集合对字符串序列进行隔空使之成为句子,要求找出所有符合要求的句子。

思路:用dp+dfs ,dp来确定每个单词的位置,而dfs则找出所有的句子。

class Solution {
    public:
        vector<string> wordBreak(string s, unordered_set<string> &dict)
        { 
            int n = s.length();
            vector<vector<int>> next(n);
            vector<bool> b(n, false);
            
            //单词尾端位置为n-1的时候需要单独拿出来测试
            for(int i = 0; i < n; i++)
            {
                if(dict.count(s.substr(i, n - i)) != 0)
                {
                    b[i] = true;
                    next[i].push_back(n - 1);
                }
            }
            //从右往左依次测试符合要求的单词位置
            for(int i = n - 1; i >= 0; i--)
            {
                for(int j = i - 1; j >= 0; j--)
                    if(b[i] && dict.count(s.substr(j, i - j)))
                    {
                        b[j] = true;
                        next[j].push_back(i - 1);
                    }
            }
            string rs;
            vector<string> svec;
            dfs(0, rs, next, svec, s);
            return svec;
        }
        void dfs(int index, string &rs, vector<vector<int>> &next, vector<string> &svec,
            string &target)
        {
            int n = target.size();
            if(index >= n)
            {
                svec.push_back(rs);
                return;
            }
            int c = next[index].size();
            for(int i = 0; i < c; i++)
            {
                int cursize = rs.size();
                rs.insert(rs.end(), target.begin() + index, target.begin() + next[index][i] + 1);
                //假如不是最后一个单词 则加空格
                if(next[index][i] < n - 1)
                    rs.push_back(' ');
                dfs(next[index][i] + 1, rs, next, svec, target);
                rs.resize(cursize);
            }
        }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值