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"]
.
牺牲内存换时间,有时是值得的,要吝惜空间,不要吝啬空间!
class Solution {
public:
int maxlen;
unordered_map<int,vector<string> >okword;
unordered_map<int, bool>avail;
vector<string> wordBreak(string s, unordered_set<string> &dict) {
vector<string> rst;
if(s.size() == 0 || dict.size() == 0)return rst;
okword.clear();
avail.clear();
maxlen = 0;
for(unordered_set<string>::iterator it = dict.begin(); it != dict.end(); ++it)
{
if(maxlen < it->size())maxlen = it->size();
}
if(caculate_okwords(0, s, dict))
{
string str;
generate_rst(0, s.size(), str,rst);
}
return rst;
}
//功能分开,更清楚高效,内聚越高越好,能分开的模块就分出来
void generate_rst(int i, int size,string &sentence, vector<string> &rst)
{
if(i == size)
{
rst.push_back(sentence);
return;
}
vector<string> strs = okword[i];
for(int idx = 0; idx < strs.size(); ++idx)
{
string tmp = sentence;
if(i) sentence += " ";
sentence += strs[idx];
generate_rst(i + strs[idx].size(), size, sentence, rst);
sentence = tmp;
}
return ;
}
bool caculate_okwords(int i,string s, unordered_set<string> &dict)
{
if(i == s.size())return true;
if(avail.find(i) != avail.end())return avail[i];
int flag = 0;
for(int len = 1; len <= maxlen && i + len <= s.size(); ++len)
{
string str = s.substr(i, len);
if(dict.find(str) != dict.end())
{
bool rst = caculate_okwords(i + len, s, dict);
if(rst)
{
flag = 1;
okword[i].push_back(str);
avail[i] = true;
}
}
}
if(flag)return true;
avail[i] = false;//记得保存false的结果
return false;
}
};