Word Break
2015-07-31 14:36
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
s =
dict =
Return true because
利用动态规划算法,创建一个vector记录0-i的字符串是否可以由字典中的词组成,若可以则继续判断剩下的是否可以由字典词组成。为防止s的一部分可以分割而另一部分不可分割,需全部遍历一遍s,而不能根据i跳跃遍历。
For example, given
s =
"leetcode",
dict =
["leet", "code"].
Return true because
"leetcode"can be segmented as
"leet code".
利用动态规划算法,创建一个vector记录0-i的字符串是否可以由字典中的词组成,若可以则继续判断剩下的是否可以由字典词组成。为防止s的一部分可以分割而另一部分不可分割,需全部遍历一遍s,而不能根据i跳跃遍历。
class Solution { public: bool wordBreak(string s, unordered_set<string>& wordDict) { int n=s.length(); if(n<1) return true; if(wordDict.empty()) return false; vector<bool> dp(n+1,false); dp[0]=true; for(int i=0;i<n;i++) { if(dp[i]) { for(int j=i;j<n;j++) { string tmps=s.substr(i,j-i+1); if(wordDict.count(tmps)) dp[j+1]=true; } } } return dp ; } };
相关文章推荐
- 详解Grunt插件之LiveReload实现页面自动刷新(两种方案)
- html嵌套php:switch
- 红帽企业虚拟化管理平台RHEVM安装指南(精简版)
- 如何安装家庭媒体中心 Plex Media Server
- Linux基金会新近成立的云原生计算基金会隐藏着什么名堂?
- Linux基金会新近成立的云原生计算基金会隐藏着什么名堂?
- oracle 10g不支持 continue解决方法
- ZOJ 2723 Semi-Prime (素数筛选大法)
- HBase - 数据模型的特殊属性 | 那伊抹微笑
- 消息中间件(二)---ActiveMQ
- ClassLoader详解及用途
- Can't connect to MySQL server on 'XXX' (13)
- 使用Timer新线程定时查询数据库
- Oracle 学习之RMAN(九)BACKUP常用参数
- PCIe SSD KVM IO性能调优
- OpenSSL编程-RSA编程详解
- spring常用注解
- 程序员如何爱护自己的眼睛
- windows cmd批处理
- VM虚拟机错误:Transport(VMDB)error -44:Message