Word Break II

来源:互联网 发布:淘宝怎么改价钱 编辑:程序博客网 时间:2024/06/18 08:06

Given a string s and a dictionary of words dict, add spaces ins 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"].


Solution:

class Solution {public:    vector<string> wordBreak(string s, unordered_set<string>& wordDict) {        vector<string> res;        unordered_set<string> unmatch;        int minN = 0x3fffffff, maxN = 0xffffffff;        for(auto d : wordDict)        {            minN = min(minN, (int)d.length());            maxN = max(maxN, (int)d.length());        }        dfs(s, wordDict, unmatch, "", res, minN, maxN);                return res;    }        void dfs(string s, unordered_set<string> &wordDict, unordered_set<string> &unmatch, string str, vector<string> &res, int minN, int maxN)    {        if(!s.length())        {            if(!str.empty()) res.push_back(str.substr(0, str.length() - 1));            return ;        }        for(int i = minN; i <= min(maxN, (int)s.length()); ++i)        {            string prefix = s.substr(0, i);            if(!wordDict.count(prefix)) continue;            else            {                string postfix = s.substr(i);                if(unmatch.count(postfix)) continue;                else                {                    int num = res.size();                    dfs(postfix, wordDict, unmatch, str + prefix + " ", res, minN, maxN);                    if(res.size() == num) unmatch.insert(postfix);                }            }        }    }};


0 0
原创粉丝点击