LeetCode ||& Word Break && Word Break II(转)——动态规划
一、
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) {
int len=s.length();
vector<bool> v(len+,false);
v[]=true;
for(int pos=;pos<len;pos++){
for(int i=pos;v[pos]&&i<len;i++){
if(dict.find(s.substr(pos,i-pos+))!=dict.end())
v[i+]=true;
}
}
return v[len];
}
};
二、
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].
A solution is ["cats and dog", "cat sand dog"].
即不仅要确定字符串是否能被字典分割,还要找出所有可能的组合。参考word break那题的DP思路,首先,从尾部开始逆向看字符串 s ,循环截取一个存在的词(milestone 1),然后在截取的位置递归,继续向前看,继续截取。。。知道到达头部,此时组合出一种答案;然后进入milestone 1 处的下一次循环,如下图的milestone 1‘,截取另外一个词,找另外一个答案。。。
代码如下:
class Solution {
vector<string> midres;
vector<string> res;
vector<bool> *dp;
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
int len = s.length(); dp = new vector<bool>[len];
for(int i=; i<len; ++i){
for(int j=i; j<len; ++j){
if(dict.find(s.substr(i, j-i+))!=dict.end()){
dp[i].push_back(true); //第二维的下标实际是:单词长度-1
}else{
dp[i].push_back(false); //数组第二维用vector,size不一定是n,这样比n*n节省空间
}
}
}
func(s, len-);
return res;
} void func(const string &s, int i){
if(i>=){
for(int j=; j<=i; ++j){ if(dp[j][i-j]){ //注意此处的第二个下标是 i-j,不是i,因为数组的第二维长度是不固定的,第二维的下标实际是单词长度-1 midres.push_back(s.substr(j, i-j+));
func(s, j-);
midres.pop_back(); //继续考虑for循环的下一个分段处
}
}
return;
}
else{
string str;
for(int k=midres.size()-; k>=; --k){ //注意遍历的顺序是倒序的
str += midres[k]; //注意此处是k,不是i
if(k>)
str += " ";
}
res.push_back(str);
return;
}
}
};
注意递归函数的技巧,用全局变量res来保存答案,每次递归成功到达头部时将此中间结果保存到res。
转自:http://blog.csdn.net/jiadebin890724/article/details/34829865
LeetCode ||& Word Break && Word Break II(转)——动态规划的更多相关文章
- leetcode 940. 不同的子序列 II (动态规划 ,字符串, hash,好题)
题目链接 https://leetcode-cn.com/problems/distinct-subsequences-ii/ 题意: 给定一个字符串,判断里面不相同的子串的总个数 思路: 非常巧妙的 ...
- 【LeetCode】140. Word Break II 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归求解 日期 题目地址:https://leetc ...
- [leetcode]244. Shortest Word Distance II最短单词距离(允许连环call)
Design a class which receives a list of words in the constructor, and implements a method that takes ...
- [LeetCode] 244. Shortest Word Distance II 最短单词距离 II
This is a follow up of Shortest Word Distance. The only difference is now you are given the list of ...
- 【一天一道LeetCode】#79. Word Search
一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...
- LeetCode 5:Given an input string, reverse the string word by word.
problem: Given an input string, reverse the string word by word. For example: Given s = "the sk ...
- [LeetCode] 243. Shortest Word Distance 最短单词距离
Given a list of words and two words word1 and word2, return the shortest distance between these two ...
- [LeetCode] 245. Shortest Word Distance III 最短单词距离 III
This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as ...
- leetcode面试准备: Word Pattern
leetcode面试准备: Word Pattern 1 题目 Given a pattern and a string str, find if str follows the same patte ...
- LeetCode OJ:Word Search(单词查找)
Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from l ...
随机推荐
- 快速入门Matplotlib
十分钟快速入门Matplotlib 函数式绘图 这个库主要有两种绘图方式,一种是像这样的类matlab的函数式绘图方法. import matplotlib.pyplot as plt import ...
- Java技术——Java中的内存泄漏
. OOM的常见类型 按照JVM规范,JAVA虚拟机在运行时会管理以下的内存区域: 程序计数器:当前线程执行的字节码的行号指示器,线程私有. JAVA虚拟机栈:Java方法执行的内存模型,每个Java ...
- 转:Ubuntu下ibus-sunpinyin的安装及翻页快捷键设置!
在windows下,好多人都已经习惯了使用搜狗拼音,到ubuntu下,忽然没有极为顺手的输入法,实为郁闷,但是确实还没有for linux版本的搜狗使用,这是搜狗的商业策略,我们无法掌控,但是,如果你 ...
- 大数据学习——本地安装redis
下载安装包 https://github.com/MicrosoftArchive/redis 下载后解压 运行cmd 然后到redis路径 运行命令: redis-server redis.wind ...
- 【LeetCode】Add Two Numbers(两数相加)
这道题是LeetCode里的第2道题. 题目要求: 给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字. 如果,我们将 ...
- xtu数据结构 I. A Simple Tree Problem
I. A Simple Tree Problem Time Limit: 3000ms Memory Limit: 65536KB 64-bit integer IO format: %lld ...
- 常州模拟赛d5t2 mogician
分析:一个暴力的思想是枚举g,然后枚举每个数ai,看能不能符合要求,这样复杂度是O(nA)的,直接T掉了.也没什么其他的办法了,在暴力的基础上优化一下,优化的关键是要如何快速统计出不满足要求的数的个数 ...
- 常州模拟赛d1t5 遗忘口令
就像每个人都会遇到的问题一样,贝西忘了在 cowtube 上的口令.不过,她还记着一些关于口令 的信息.首先,她确定口令由小写字母组成,长度为 L.其次,这个密码是由几个单词组合而成 的.贝西一共认识 ...
- mysql查询死锁,执行语句,服务器状态等语句集合
[转]http://blog.csdn.net/enweitech/article/details/52447006
- 货车运输(codevs 3287)
题目描述 Description A 国有 n 座城市,编号从 1 到 n,城市之间有 m 条双向道路.每一条道路对车辆都有重量限制,简称限重.现在有 q 辆货车在运输货物,司机们想知道每辆车在不超过 ...