首页 > 其他 > 详细

[LeetCode]Word Break II

时间:2014-03-13 00:50:48      阅读:430      评论: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"].

参考:http://blog.csdn.net/doc_sgl/article/details/13064739

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
public:
    void wordBreakHelper(string s,unordered_set<string> &dict,set<string> &unmatched,
        int mn,int mx, vector<string> &path, vector<string> &res) {
        int i = mx < s.length() ? mx : s.length();
        for(; i >= mn ; i--)
        {
            string preffixstr = s.substr(0,i);
            if(dict.find(preffixstr) != dict.end()){
                path.push_back(preffixstr);
                if(preffixstr.size() == s.size())
                {
                    string tmp = path[0];
                    for(int i=1; i<path.size(); i++)
                        tmp+= " "+path[i];
                    res.push_back(tmp);
                }
                string suffixstr = s.substr(i);
                if(unmatched.find(suffixstr) == unmatched.end())
                {
                    int oldsz = res.size();
                    wordBreakHelper(suffixstr,dict,unmatched,mn,mx,path,res);
                    if(res.size() == oldsz)
                        unmatched.insert(suffixstr);
                }
                path.pop_back();
            }
        }
    }
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
        // Note: The Solution object is instantiated only once.
        vector<string> res;
        if(s.size() < 1 || dict.empty()) return res;
        unordered_set<string>::iterator it = dict.begin();
        int maxlen=(*it).length(), minlen=(*it).length();
        for(it++; it != dict.end(); it++)
            if((*it).length() > maxlen)
                maxlen = (*it).length();
            else if((*it).length() < minlen)
                minlen = (*it).length();
        set<string> unmatched;
        vector<string> path;
        wordBreakHelper(s,dict,unmatched,minlen,maxlen,path,res);
        return res;
    }
};

  

[LeetCode]Word Break II,布布扣,bubuko.com

[LeetCode]Word Break II

原文:http://www.cnblogs.com/Rosanna/p/3597249.html

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