首页 > 其他 > 详细

Word Break II

时间:2014-01-23 07:56:51      阅读:381      评论:0      收藏:0      [点我收藏+]

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。

class Solution {
public:
    void dfs(string s, int start, vector<string>& re, string &cur_re, unordered_set<string> &dict){
        if(start < 0) return;
        int len = s.length();
        //from back to front
        for(int i = start; i >= 0; --i){
            string sub = s.substr(i, start - i + 1);
            if(dict.find(sub) != dict.end()){
                int len = cur_re.length();
                cur_re.insert(0, " "+sub);
                dfs(s, i - 1, re, cur_re, dict);
                //恢复先前的内容,便于回退
                cur_re = cur_re.substr(cur_re.length() - len);
            }
        }
        if(dict.find(s.substr(0, start + 1)) != dict.end()){
            cur_re.insert(0, s.substr(0, start + 1));
            re.push_back(cur_re);
        }
    }
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
        vector<string> re;
        string cur_re;
        dfs(s, s.length() - 1, re, cur_re, dict);
        return re;
    }
};

更多dfs和leetcoded参见http://liaoxl.github.io/blog/categories/leetcode/

Word Break II

原文:http://blog.csdn.net/shiquxinkong/article/details/18676385

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!