[leetcode] 139.Word Break
2015-09-01 13:23
411 查看
题目:
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[i]代表的是前i个字符能够通过字典形成。
DP[i] = true; if(DP[j] = true && s.substr(j, i - j) in the dictionary。
以上。
代码如下:
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[i]代表的是前i个字符能够通过字典形成。
DP[i] = true; if(DP[j] = true && s.substr(j, i - j) in the dictionary。
以上。
代码如下:
class Solution { public: bool wordBreak(string s, unordered_set<string>& wordDict) { if(s.empty())return true; vector<bool> DP(s.length() + 1, false); DP[0] = true; for(int i = 1; i <= s.length(); i++) { for(int j = 1; j <= i && !DP[i]; j++) { if(DP[i - j] && wordDict.find(s.substr(i - j, j)) != wordDict.end())DP[i] = true; } } return DP[s.length()]; } };
相关文章推荐
- 感觉很好用”Anti_TexturePacker v1.7“
- 文章标题
- ASPose导出excel简单操作
- 2015.09.01
- Glibc辅助运行库 (C RunTime Library): crt0.o,crt1.o,crti.o crtn.o,crtbegin.o crtend.o
- 有符号与无符号讨论
- 通过JSON数据加载服务器端图片
- leetcode Add Two Numbers
- 在“JDI Event Dispatch”期间发生了内部错误。 java.lang.NullPointerException
- java excel导出向后台请求方式
- MapReduce 原理及其工作流程
- SB程序媛学习笔记--Android zxing实现二维码开发
- web开发基础
- qsort函数用法
- 对解决一般问题思考方式的一些想法
- mac出现 git permission user1 git/repo to deny user2
- Centos 6.5 安装nginx日志分析系统 elasticsearch + logstash + redis + kibana
- 【占坑】Pre-train 与 Fine-tuning
- CSS Reset
- [Leetcode]Bitwise AND of Numbers Range