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"].
#include<iostream>
#include<vector>
#include<string>
using namespace std;
#include<unordered_set>
#if 0
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
vector<string> v;
string ss = "";
for (unordered_set<string>::iterator it=dict.begin();it!=dict.end();it++)
{
int pos=s.find(*it);
int poss = ss.find(*it);
if (poss >= 0)
{
break;
}
else if (pos >= 0)
{
ss += (*it)+" ";
/*int n = pos + (*it).size();
int m = s.size();*/
}
}
v.push_back(ss);
return v;
}
};
#endif
#if 1
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) { //catsanddog
vector<string> result;
if (dict.find(s) != dict.end())
result.push_back(s);
for (int i = 1; i<s.size(); i++)
{
string w = s.substr(i); //截取i之后的字符串
if (dict.find(w) == dict.end())
continue;
string str = s.substr(0, i);
vector<string> left = wordBreak(str, dict);
Add(left, w);
//void insert( iterator loc, input_iterator start, input_iterator end )
//在指定位置loc前插入区间[start, end)的所有元素
result.insert(result.begin(), left.begin(), left.end());
}
return result;
}
void Add(vector<string> &str, string w)
{
for (vector<string>::iterator it = str.begin(); it != str.end(); it++)
*it += " " + w;
}
};
int main()
{
string s = "catsanddog";
unordered_set<string> dict;
dict.insert("cat");
dict.insert("cats");
dict.insert("and");
dict.insert("sand");
dict.insert("dog");
dict.insert("cat");
vector<string> v =Solution().wordBreak(s, dict);
for (vector<string>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << endl;
}
return 0;
}
#endif