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:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
int len = s.size();
vector<vector<bool>> flag(len, vector<bool>(len, false));
for(int i = 0; i < len; i++)
{
for(int j = 0; j < len; j++)
{
if(dict.find(s.substr(i,j-i+1)) != dict.end())
flag[i][j] = true;
}
}
vector<string> result;
for(int i = len-1; i >= 0; i--)
{
if(flag[i][len-1])
{
string str = s.substr(i, len-i);
back(flag, i-1, s, str, result);
}
}
return result;
}
void back(vector<vector<bool>> &flag, const int &i, const string &s, string str, vector<string> &result)
{
if(i==-1)
{
result.push_back(str);
return;
}
for(int j = 0; j <= i; j++)
{
if(flag[j][i])
{
string cur_str = s.substr(j, i-j+1) + " " + str;
back(flag, j-1, s, cur_str, result);
}
}
}
};

本文介绍了一种算法,该算法能够将一个字符串通过查找字典中的有效词汇进行拆分,并返回所有可能的句子组合。示例中使用了字符串“catsanddog”及字典[catcatsandsanddog]进行演示。
1575

被折叠的 条评论
为什么被折叠?



