123_leetcode_Word Break II

来源:互联网 发布:苏州基本办公软件 编辑:程序博客网 时间:2024/05/23 19:14

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

1:注意特殊情况;2:计算出dict中单词的最长和最短长度;3:使用动态规划的方法;4:记录字符串是否是已经为不满足条件的遍历


    vector<string> wordBreak(string s, unordered_set<string> &dict)    {        vector<string> result;        if(s.length() < 1 || dict.size() == 0)        {            return result;        }                unordered_set<string>::iterator itr = dict.begin();                unsigned long maxLength = (*itr).length();        unsigned long minLength = (*itr).length();                while(++itr != dict.end())        {            if ((*itr).length() > maxLength)            {                maxLength = (*itr).length();            }            if((*itr).length() < minLength)            {                minLength = (*itr).length();            }        }                set<string> unMatch;        vector<string> path;                wordBreakCore1(s, dict, unMatch, maxLength, minLength, result, path);                return result;    }        void wordBreakCore1(string s, unordered_set<string> &dict, set<string> &unMatch, unsigned long maxLength, unsigned long minLength, vector<string> &result, vector<string> &path)    {        if(s.size() == 0)        {            return;        }                unsigned long mx = s.length() < maxLength ? s.length() : maxLength;                for(int i = (int)mx; i >= minLength; i--)        {            string tmpWord = s.substr(0, i);            if(dict.find(tmpWord) != dict.end())            {                path.push_back(tmpWord);                if(tmpWord.length() == s.length())                {                    string tmp = path[0];                    for(int j = 1; j < (int)path.size(); j++)                    {                        tmp = tmp + " ";                        tmp = tmp + path[j];                    }                    result.push_back(tmp);                }                                string leftStr = s.substr(i);                if(unMatch.find(leftStr) == unMatch.end())                {                    int number = (int)result.size();                    wordBreakCore1(leftStr, dict, unMatch, maxLength, minLength, result, path);                    if(number == (int)result.size())                    {                        unMatch.insert(leftStr);                    }                }                path.pop_back();            }        }    }


0 0
原创粉丝点击