Word Break II
来源:互联网 发布:快递单统计软件 编辑:程序博客网 时间:2024/06/06 12:07
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[i][j]表示从i到j的字符串是否在字典中。
这是以题目举得一个例子,此张表中的0,1就是dp的表示,红框和绿框表示第一轮和第二轮寻找(从下往上)。具体代码和注释如下,解释很麻烦,希望可以看懂:
class Solution {
public:
vector<bool>*dp;
vector<string>mystring;
vector<string>result;
vector<string> wordBreak(string s, unordered_set<string> &dict){
dp = new vector<bool>[s.size()]; //定义一个二维数组
for (int i = 0;i<s.size();i++)
{
for (int j = i;j<s.size();j++)
{
if (dict.find(s.substr(i,j-i+1))!=dict.end()) //在字典中一次查找此单词是否存在
dp[i].push_back(true);
else
dp[i].push_back(false);
}
}
Output(s.size()-1,s); //将存在的单词按照句子的形式表示出来,我觉得这才是最难的地方
return result;
}
void Output(int index,string s)
{
if(index == -1) //如果索引值为-1,也就是说上一个单词已经从0开始了,那么就要组合找到的单词
{
string str;
for (int i = mystring.size()-1;i>=0;i--) //组合比较简单
{
str += mystring[i];
if (i!=0)
- Word Break && Word Break II
- Word Break && Word Break II
- [leetcode]Word Break II
- Word Break II
- Word Break II
- LeetCode:Word Break II
- Word Break II
- Leetcode: Word Break II
- [LeetCode] Word Break II
- [LeetCode]Word Break II
- LeetCode | Word Break II
- Word Break II
- Word Break II
- [LeetCode] - Word Break II
- LeetCode - Word Break II
- Leetcode Word Break II
- Word Break II
- Word Break II
- 如何用fiddler2捕获移动设备上的http或者https请求
- 结构体拷贝
- MYSQL远程登录权限设置
- Effective C++ Item 5 了解 C++ 默默编写并调用哪些函数
- android快速开发框架
- Word Break II
- A+B Problem III
- Remove Element,Remove Duplicates frm Sorted Array I,II(List I,II),Valid Parentheses,ZigZag Conv
- HDU 4411 Arrest 最小费用流
- 易飞9.07衍生字段删除问题
- 简单http_server的C语言实现
- python语法,以缩进分块!
- MFC消息映射机制
- 修改eclipse的背景色