class Solution {
vector<string> res;
vector<string> midRes;
// whether string s[0][j] is breakable
vector<bool> flg;
/*
Whether string s[i][j] is in dict.
Only when s[0][[i-1] is breakable and s[i][j] is in dict,
will s[i][j] be set to true.
*/
vector<bool> *midFlg;
void dfs(const string &s, int idx) {
if (idx >= 0) {
for (int j = 0; j <= idx; ++j) {
if ( midFlg[j][idx - j] ) {
midRes.push_back(s.substr(j, idx - j + 1));
dfs(s, j - 1);
midRes.pop_back();
}
}
} else {
string str;
for (int k = midRes.size() - 1; k >= 0; --k) {
str += midRes[k];
if (k > 0) {
str += " ";
}
}
res.push_back(str);
return;
}
}
public:
/**
* @param s a string
* @param wordDict a set of words
*/
vector<string> wordBreak(string s, unordered_set<string> &wordDict) {
int len = s.length();
midFlg = new vector<bool>[len];
int i, j;
// i is 0.
for (j = 0; j < len; ++j) {
if (wordDict.find(s.substr(0, j + 1)) != wordDict.end() ) {
midFlg[0].push_back(true);
flg.push_back(true);
} else {
midFlg[0].push_back(false);
flg.push_back(false);
}
}
// i >= 1
for (i = 1; i < len; ++i) {
for (j = i; j < len; ++j) {
if ( flg[i - 1] && (wordDict.find(s.substr(i, j - i + 1)) != wordDict.end()) ) {
midFlg[i].push_back(true);
flg[j] = true;
} else {
midFlg[i].push_back(false);
}
}
}
dfs(s, len - 1);
delete []midFlg;
return res;
}
};
vector<string> res;
vector<string> midRes;
// whether string s[0][j] is breakable
vector<bool> flg;
/*
Whether string s[i][j] is in dict.
Only when s[0][[i-1] is breakable and s[i][j] is in dict,
will s[i][j] be set to true.
*/
vector<bool> *midFlg;
void dfs(const string &s, int idx) {
if (idx >= 0) {
for (int j = 0; j <= idx; ++j) {
if ( midFlg[j][idx - j] ) {
midRes.push_back(s.substr(j, idx - j + 1));
dfs(s, j - 1);
midRes.pop_back();
}
}
} else {
string str;
for (int k = midRes.size() - 1; k >= 0; --k) {
str += midRes[k];
if (k > 0) {
str += " ";
}
}
res.push_back(str);
return;
}
}
public:
/**
* @param s a string
* @param wordDict a set of words
*/
vector<string> wordBreak(string s, unordered_set<string> &wordDict) {
int len = s.length();
midFlg = new vector<bool>[len];
int i, j;
// i is 0.
for (j = 0; j < len; ++j) {
if (wordDict.find(s.substr(0, j + 1)) != wordDict.end() ) {
midFlg[0].push_back(true);
flg.push_back(true);
} else {
midFlg[0].push_back(false);
flg.push_back(false);
}
}
// i >= 1
for (i = 1; i < len; ++i) {
for (j = i; j < len; ++j) {
if ( flg[i - 1] && (wordDict.find(s.substr(i, j - i + 1)) != wordDict.end()) ) {
midFlg[i].push_back(true);
flg[j] = true;
} else {
midFlg[i].push_back(false);
}
}
}
dfs(s, len - 1);
delete []midFlg;
return res;
}
};