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"]
.
dp完以后得到dp数组,然后根据dp数组构造可能的sentence即可。
class Solution {
public:
int len=0;
vector<string> v;
bool* f;
vector<string> wordBreak(string s, unordered_set<string> &dict) {
// Note: The Solution object is instantiated only once and is reused by each test case.
word(s,dict);
if(!f[s.length()])
return v;
build(s,s.length(),"",dict);
return v;
}
void build(string s,int index,string cur,unordered_set<string> &dict){
if(index==0){
v.push_back(cur.substr(0,cur.length()-1));
return;
}
for(int i=1;i<=len && index-i>=0;i++){
if(find(s.substr(index-i,i),dict) && f[index-i]){
build(s,index-i,s.substr(index-i,i)+" "+cur,dict);
}
}
}
bool find(string s,unordered_set<string> &dict){
unordered_set<string>::iterator it = dict.find(s);
return it!=dict.end();
}
void word(string s, unordered_set<string> &dict) {
string str;
for(unordered_set<string>::iterator it = dict.begin();it!=dict.end();it++){
str = *it;
len = max((int)str.length(),len);
}
f = new bool[s.length()+1];
f[0] = true;
for(int i=0;i<s.length();i++){
for(int j=1;i+1-j>=0 && j<=len;j++){
f[i+1] = f[i+1-j] && find(s.substr(i+1-j,j),dict);
if(f[i+1])
break;
}
}
}
};