题目一:
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet
code".
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"].
分析:
几点题目要求需要领会:
1)存储单词集合的set是无顺序的,所以不能从set中开始挨个寻找单词在组合词是否存在。
2)set中的词可以在组合词中重复出现。
本题是从组合词中挨个单词进行寻找:
代码如下:
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict)
{
int len = s.size();
vector<bool>m_vec(len+1,false);
m_vec[0] = true;
int i = 0;
int j = 0;
for (i = 1;i < len+1;i++)
{
for (j = i-1;j>=0;j--)
{
if (m_vec[j] && dict.find(s.substr(j,i-j))!=dict.end())
{
m_vec[i] = true;
break;
}
}
}
return m_vec[i-1];
}
};题目二:
思路:
1)找出组合词中,存在单词的起始位置,用一个二维数组表示,比如prev[i][j]表示从j到i中的字符串是个单词。
2)在用循环递归的方式插入寻找出答案。
3)在循环递归中,注意清理先前存入的数据。
代码如下:
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
int len = s.size();
int i = 0;
int j = 0;
vector<bool>m_vec(len+1,false);
m_vec[0] = true;
vector<vector<bool>>m_prevec(len+1,vector<bool>(len));
for(i=1;i<len+1;i++)
{
for(j=i-1;j>=0;j--)
{
if(m_vec[j]&&dict.find(s.substr(j,i-j))!=dict.end())
{
m_vec[i]=true;
m_prevec[i][j]=true;
}
}
}
vector<string>path;
gen_path(s,m_prevec,len,path);
return m_strvec;
}
private:
vector<string>m_strvec;
void gen_path(string &s,const vector<vector<bool>>&prev,int len,vector<string>&path)
{
if (len == 0)
{
string str;
for (vector<string>::reverse_iterator pos = path.rbegin();pos!=path.rend();pos++)
{
str.append(*pos);
str.append(" ");
}
str.erase(--str.end());
m_strvec.push_back(str);
}
for (int i=0;i<s.size();i++)
{
if (prev[len][i])
{
path.push_back(s.substr(i,len-i));
gen_path(s,prev,i,path);
path.pop_back();
}
}
}
};
209




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



