Word Break
2015-08-16 22:28
381 查看
题目139:Word Break
题目描述: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”.
思路分析:
动态规划,假设res[i]表示长度为i的string能否被切分,也可以理解为下标i以前的字符串能否被切分。动态规划思想,假设现在已经知道res[0]、res[1]……res[i-2]、res[i-1],那如何能求出res[i]。
以res[i-1]为例说明,假设res[i-1]是真,则string中下标0~i-2可以被切分成都在字典里,不妨设在下标j处刚好可以切分,则将string切分成左右两边,string[0~j]对应的word1和string[j+1~i-1]对应的word2,word1和word2都在字典中,如果string[i]对应的word3刚好也在字典种,则res[i]是真;如果word3不在字典中,则换下一个res[k]。
不知道我讲清楚了没有,最后可以得出的是:
res[i] = res[k] && string.substr(k, i - k)是否在字典中;
注意:求子串时下标是从k开始,因为res[k]表示的是长度为k的字符串,下标刚好到k-1。
class Solution { public: bool wordBreak(string s, unordered_set<string>& wordDict) { int len = s.length(); if (0 == len) return false; vector<bool> res(len + 1, false); /* 无奈的初始化,切分时如果左边是空,右边是整个字符串时,判断是否可以被切分,需要判断res[0],所以res[0]必须是真,不会影响结果 */ res[0] = true; int i, j; for (i = 1; i <= len + 1; i ++) { for (j = i - 1; j >= 0; -- j) { if (res[j] && wordDict.find(s.substr(j, i - j)) != wordDict.end()) { res[i] = true; break; } } } return res[len + 1]; } };
参考:
[1] http://www.hihuyue.com/hihuyue/codepractise/leetcode/leetcode144-word-break
[2] http://blog.sina.com.cn/s/blog_eb52001d0102v2hp.html
[3] http://www.cnblogs.com/lautsie/p/3371354.html
相关文章推荐
- [Leetcode]Word Break & Word Break II
- LeetCode:Word Break II
- leetcode之 wordBreak(1)解决思路
- 五大经典算法之三动态递归DP
- Microsoft Dynamics CRM 2015 数据管理 功能 介绍
- Microsoft Dynamics CRM 2015 数据管理 功能 介绍
- 函数指针C++和回调函数
- 在VMware做虚拟映射进行网络连接的步骤
- 梦想永远那么近——《白箱》后日谈
- 机房重构VB.Net版进行中
- MongoDB查询内嵌文档
- glibc源码
- HDU 2276 & FZU 1692 (矩阵快速幂+循环同构优化)
- [线段树]hdu5316
- SpringMVC+MyBatis整合(3)特别篇SpringMVC配置
- ArrayAdapter的使用
- python使用libssh2连接linux
- 项目实战之玩转div+css制作自定义形状
- 在Ubuntu上配置django环境系统架构命令
- vijos - P1286座位安排 (DP状态压缩 + 组合数 + python)