leetcode笔记:Word Break
2016-01-25 23:48
351 查看
一. 题目描述
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
Return true because
二. 题目分析
如果使用递归,会超时。这时使用动态规划即可解决问题,即将源字符串s从开始到结尾,分解成各个子串进行操作,对于这类字符串组合问题,需要掌握类似状态转移方程。对于下标
三. 示例代码
四. 小结
动态规划对于解决一些字符串的问题也是有效且容易实现的。
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".
二. 题目分析
如果使用递归,会超时。这时使用动态规划即可解决问题,即将源字符串s从开始到结尾,分解成各个子串进行操作,对于这类字符串组合问题,需要掌握类似状态转移方程。对于下标
i所对应字符的匹配状态
flag[i],如果dict有字符串可以匹配,这取决于之前某个字符
j的状态出现匹配,且从数组s的
j + 1到
i下标之间的字符也能从dict中找到匹配的字符串:
flag[i] = any(flag[j] && (s[j + 1, i] ∈ dict))
三. 示例代码
[code]class Solution { public: bool wordBreak(string s, unordered_set<string> &dict) { vector<bool> wordFlag(s.size() + 1, false); // 动态规划 wordFlag[0] = true; for (int i = 1; i < s.size() + 1; ++i) { for (int j = i - 1; j >= 0; --j) { if (wordFlag[j] && dict.find(s.substr(j, i - j)) != dict.end()) { wordFlag[i] = true; break; } } } return wordFlag[s.size()]; } };
四. 小结
动态规划对于解决一些字符串的问题也是有效且容易实现的。
相关文章推荐
- 20160122.CCPP详解体系(0001天)
- JavaScript判断浏览器类型
- 图像处理之让手心长出眼睛,其实嘴也可以~
- 真机调试时遇到“Could not launch *** process launch failed: Security”的解决办法
- 【更改表单元素默认样式】更改自定义文件上传按钮样式
- forever让nodejs应用后台执行
- Cordova学习——使用jquery框架+device设备插件完整过程
- Ubuntu 的 desktop 和 server 还是有区别。
- Cocos Sprite创建的5种方法
- ISE PhysDesignRules
- Data Integration - Kettle 6.0下载安装
- 在Eclipse中使用JUnit4进行单元测试(初级篇)
- POJ2349(求生成树中符合题意的边)
- 【莫队算法】[CodeForces - 617E/Round #340]XOR and Favorite Number
- nyoj301——递推求值
- Python数据分析学习路径图(120天Get新技能)
- linux服务器性能运维
- 第四章 单位和值
- Codeforces Round #340 (Div. 2) D. Polyline(规律)
- 第三章 结构和层叠