leetcode 139. Word Break
2016-06-18 14:23
260 查看
题目
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".
解题思路-DP
递推公式如下:考虑 string 的前 n 个字符,对于第 i 个字符( i 包含于 [0, n) ),如果在 DP 表 table 中, table[i] 的取值为真,并且 [i,n) 也是字典中的单词,那么 [0,n) 的结果就为真。
代码
bool wordBreak(const string s, const unordered_set<string>& wordDict) { vector<bool> table(s.size() + 1, false); //DP表,用来存储前驱结点的解 table[0] = true; for (string::size_type end = 0; end < s.size(); end++) { for (string::size_type beg = 0; beg <= end; beg++) { string temp = s.substr(beg, end - beg + 1); bool prev = table[beg]; if (prev && wordDict.find(temp) != wordDict.cend()) { table[end + 1] = true; break; } } } return table[s.size()]; }
相关文章推荐
- SQL 树结构统计数据
- NSArray其中的方法--遍历,
- Caffe + Ubuntu 15.04 + CUDA 7.5 新手安装配置指南
- JAVA_OA(六):SpringMVC处理异常
- ElasticSearch 解析机制常见用法库 之 Tokenizer常用用法
- 调整数组顺序使奇数位于偶数前面
- 线程安全的集合类、CopyOnWrite机制介绍
- jQueryUI 之控件们
- 开源公司黄页之Facebook开源软件推荐(一)
- SQL循环
- 老电工教你快速学会如何看懂电气控制电路图
- java调接口实现发送手机短信验证码功能,手机验证码,接口调用
- 1Z0-051-DDL-主要数据库对象和数据类型
- 实际开发中dp , px ,pt , sp 的使用
- Leetcode题解 100. Same Tree
- Failed to install Tomcat7 service
- 第2章 进程管理
- 图片处理的一些方法
- Zeta(2)
- 第八次课总结及思考