139. Word Break 单词切分
2016-07-13 15:38
281 查看
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
1. 与之前答案相同,不要问我怎么做,因为我也是背下来的。。。
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int n = s.size();
vector<bool> label(n+1, false);
label[0] = true;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= i; j++){
if(label[i-j] == true){
string str = s.substr(i-j,j);
if(wordDict.find(str) != wordDict.end())
label[i] = true;
}
}
}
return label
;
}
};
2.别人的答案 这个比较好理解
bool wordBreak(string s, unordered_set<string> &dict) {
if(dict.size()==0) return false;
vector<bool> dp(s.size()+1,false);
dp[0]=true;
for(int i=1;i<=s.size();i++)
{
for(int j=i-1;j>=0;j--)
{
if(dp[j])
{
string word = s.substr(j,i-j);
if(dict.find(word)!= dict.end())
{
dp[i]=true;
break; //next i
}
}
}
}
return dp[s.size()];
}
For example, given
s =
"leetcode",
dict =
["leet", "code"].
Return true because
"leetcode"can be segmented as
"leet code".
1. 与之前答案相同,不要问我怎么做,因为我也是背下来的。。。
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int n = s.size();
vector<bool> label(n+1, false);
label[0] = true;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= i; j++){
if(label[i-j] == true){
string str = s.substr(i-j,j);
if(wordDict.find(str) != wordDict.end())
label[i] = true;
}
}
}
return label
;
}
};
2.别人的答案 这个比较好理解
bool wordBreak(string s, unordered_set<string> &dict) {
if(dict.size()==0) return false;
vector<bool> dp(s.size()+1,false);
dp[0]=true;
for(int i=1;i<=s.size();i++)
{
for(int j=i-1;j>=0;j--)
{
if(dp[j])
{
string word = s.substr(j,i-j);
if(dict.find(word)!= dict.end())
{
dp[i]=true;
break; //next i
}
}
}
}
return dp[s.size()];
}
相关文章推荐
- MyEclipse Web Project转Eclipse Dynamic Web Project
- DLL(Dynamic Linkable Library) 详解说明
- 深入C# 4.0 新特性dynamic、可选参数、命名参数的详细介绍
- C# Dynamic关键字之:解析dynamic就是Object
- C# Dynamic关键字之:dynamic为什么比反射快的详解
- Dynamic和Var的区别及dynamic使用详解
- C# dynamic关键字的使用方法
- PHP Warning: PHP Startup: Unable to load dynamic library \ D:/php5/ext/php_mysqli.dll\
- MariaDB扩展特性--动态列
- jenkins动态参数构建
- 编程语言进化
- DHCP Snooping + Dynamic ARP Inspection(DAI) 配置
- 架设动态 DNS 服务器: 让你成为 ISP 啦
- 关于php-fpm子进程设置
- 建立C语言动态链接库
- php-fpm的max_chindren的一些误区
- NSDictionary
- hyperv 动态磁盘的缺陷
- 五个编程语言设计的失误
- 编程语言时间地理图