LeetCode139:Word Break
题目:
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题,说实话,本人也是算法方面的菜鸟一枚,关于DP方面的题,还不太会解,没办法,只能多练习了。
这里采用DP中的两种方式实现:自顶向下和自底向上。
dp[i]表示前i个字符能否进行Wordbreak。当求解dp[i]时,可利用已经求解的dp[i-1],dp[i-2]…dp[1],dp[0]进行求解。
对于dp[n]的求解,我们可以将n个字符进行切分求解,分为前i个字符和后n-i个字符,i可以为(0,1,2,3,4…n-1)
假设i为1时,可根据dp[i]和后面的n-1个字符组成的单词是否在dict中来判断dp[n],只要i(0,1,2,3,4…n-1)其中一种
情况为真,则dp[n]为true,表示可以进行workbreak。
实现代码:
#include <iostream>
#include <string>
#include <vector>
#include <unordered_set>
using namespace std; /*
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".
*/
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
if(s.size() == || dict.size() == )
return false;
int len = s.size();
vector<bool> dp(len+, false);//保存状态,dp[i]表示前i个字符是否可以进行wordBread
dp[] = true;
for(int i = ; i <= len; i++)
for(int j = ; j < i; j++)
{
if(dp[j] && dict.count(s.substr(j, i-j)) == )//对前i个字符进行切分时,只要有一种情况为true,则dp[i]=true
{
dp[i] = true;
break;
}
}
return dp[len]; } bool wordBreak2(string s, unordered_set<string> &dict) {
if(s.size() == || dict.size() == )
return false;
int len = s.size();
vector<bool> dp(len+, false);//保存状态,dp[i]表示前i个字符是否可以进行wordBread
dp[] = true;
for(int i = ; i < len; i++)
if(dp[i])
{
for(int j = ; j <= len-i; j++)
if(dict.count(s.substr(i, j)) == )
dp[i+j] = true;
} return dp[len]; } //DP:自顶向下,
int wordBreak3_core(string s, unordered_set<string> &dict, int *dp)
{
int len = s.size();
if(dp[len] >= )
return dp[len];//如果值已经改变即不再是初始值,说明dp[len]已经求得,直接返回即可,不必再求
int isBreak;
if(len == )
isBreak = ;
else
{
int ret = ;
for(int i = ; i < len; i++)
{
if(wordBreak3_core(s.substr(, i), dict, dp) == && dict.count(s.substr(i, len-i)) == )
{
ret = ;
break;
} }
isBreak = ret; }
dp[len] = isBreak;
return isBreak;
}
//DP:自顶向下,
bool wordBreak3(string s, unordered_set<string> &dict)
{
if(s.size() == || dict.size() == )
return false;
int len = s.size();
int *dp = new int[len+];//保存状态,dp[i]表示前i个字符是否可以进行wordBread
for(int i = ; i <= len; i++)
dp[i] = -;//每个状态进行初始化
int ret = wordBreak3_core(s, dict, dp);
delete [] dp;
return ret; } }; int main(void)
{
string s("leetcode");
unordered_set<string> dict;
dict.insert("leet");
dict.insert("code");
Solution solution;
bool ret = solution.wordBreak3(s, dict);
cout<<ret<<endl; return ;
}
网上还有通过trie树实现的,这里直接引用http://www.iteye.com/topic/1132188#2402159,就不多写了
代码如下:
class Solution {
public:
class Node {
public:
Node* next[];
bool end;
Node(): end(false) { for (int i = ; i < ; i++) next[i] = NULL;}
void insert(string a) {
Node * cur = this;
for (int i = ; i < a.size(); i++) {
if (cur->next[a[i]-'a'] == NULL) {
cur->next[a[i]-'a'] = new Node();
}
cur = cur->next[a[i]-'a'];
}
cur->end = true;
}
~Node () {
for (int i = ;i < ; i++) delete next[i];
}
};
bool wordBreak(string s, unordered_set<string> &dict) {
Node root;
for (auto it = dict.begin(); it != dict.end(); ++it) {
root.insert(*it);
}
vector<bool> v(s.size(), false);
findMatch(s, &root, , v);
for (int i = ; i < s.size(); i++)
if (v[i]) findMatch(s, &root, i+, v);
return v[s.size() - ];
}
void findMatch(const string& s, Node* cur, int start, vector<bool> &v) {
int i = start, n = s.size();
while (i < n) {
if (cur->next[s[i] - 'a'] != NULL) {
if (cur->next[s[i] - 'a']->end) v[i] = true;
cur = cur->next[s[i] - 'a'];
}
else break;
i++;
}
}
};
LeetCode139:Word Break的更多相关文章
- LeetCode之“动态规划”:Word Break && Word Break II
1. Word Break 题目链接 题目要求: Given a string s and a dictionary of words dict, determine if s can be seg ...
- LeetCode140:Word Break II
题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where e ...
- leetcode笔记:Word Break
一. 题目描写叙述 Given a string s and a dictionary of words dict, determine if s can be segmented into a sp ...
- [LeetCode] Word Break II 拆分词句之二
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each ...
- word break和word wrap
默认情况下,如果同一行中某个单词太长了,它就会被默认移动到下一行去: word break(normal | break-all | keep-all):表示断词的方式 word wrap(norma ...
- 17. Word Break && Word Break II
Word Break Given a string s and a dictionary of words dict, determine if s can be segmented into a s ...
- LeetCode:Word Break II(DP)
题目地址:请戳我 这一题在leetcode前面一道题word break 的基础上用数组保存前驱路径,然后在前驱路径上用DFS可以构造所有解.但是要注意的是动态规划中要去掉前一道题的一些约束条件(具体 ...
- LeetCode Word Break II
原题链接在这里:https://leetcode.com/problems/word-break-ii/ 题目: Given a string s and a dictionary of words ...
- Leetcode#139 Word Break
原题地址 与Word Break II(参见这篇文章)相比,只需要判断是否可行,不需要构造解,简单一些. 依然是动态规划. 代码: bool wordBreak(string s, unordered ...
随机推荐
- siebel切换数据源
需求: 将SIT应用服务器10.10.1.151中配置的数据源改为测试集群数据库服务器10.10.1.53.10.10.1.54 方法: 1.将正式环境数据库17 18 的RACDB还原到测试集群服务 ...
- Dell 服务器安装方法介绍
大家都知道dell服务器在安装windows系统时都需要有raid卡驱动的加载才可以人道服务器硬盘,下面来介绍一下dell服务器raid卡驱动的加载和系统的安装: 方法一: 使用dell服务器自带的 ...
- subprocess 粘包问题
1.执行命令: 在py代码中去如何调用操作系统的命令 新模块:subprocess r = subprocess.Popen('ls',shell=True,stdout=subprocess.PIP ...
- Intellij IDEA使用Maven搭建spark开发环境(scala)
如何一步一步地在Intellij IDEA使用Maven搭建spark开发环境,并基于scala编写简单的spark中wordcount实例. 1.准备工作 首先需要在你电脑上安装jdk和scala以 ...
- Javascript读写CSS属性
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- 使用生活实例理解Asp.net运行时
学习编程语言,掌握面向对象的编程思想尤为重要,一旦理解了面向对象的这种概念,那么好些地方拿到生活中去理解,就容易的多了.书本上的枯燥干涩的语言,对于好多人来说,即难懂,更难长时间牢牢记得.但是编程语言 ...
- ubuntu 操作系统的目录结构
Ubuntu 系统的目录众多,并且 Ubuntu 系统是不分 C 盘.D 盘等的,但是所有的目录都是在/目录下面的. 一./:根目录,是所有目录的绝对路径的起始点,Ubuntu 中的所有文件和目录都在 ...
- Photoshop和Halcon中的极坐标变换
极坐标想必学过高中数学的人都听过,一般的坐标系中用(x, y)值来描述一个点的位置,而在极坐标系中,则使用到原点的距离ρ和夹角θ来描述该点的位置. 我很早就接触了Photoshop,知道Photosh ...
- tp5链接访问
方法名:admin/DayActive/statistic 访问:admin/day_active/statistic
- [BAT]win7下用批处理脚本自动删除7天以前创建的文件
set JmeterPath=D:\apache-jmeter-2.7 forfiles /p %JmeterPath%\extras /m *.html -d -7 /c "cmd /c ...