【LeetCode】140. Word Break II 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/word-break-ii/
题目描述
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:
Input:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output:
[
"cats and dog",
"cat sand dog"
]
Example 2:
Input:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
Output:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
Explanation: Note that you are allowed to reuse a dictionary word.
Example 3:
Input:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
Output:
[]
题目大意
给了一个字典,问给定的字符串s能有多少种被字典构造出来的方式,返回每一种构造方式。
解题方法
递归求解
这个题就是139. Word Break的变形,现在要求所有的构造方式了。
一般这种题就需要使用递归,把所有的构造方式都求出来。这个题必须使用字典保存已经能切分的方式,否则,递归的时间复杂度太高。我们定义函数dfs,其含义是字符串s能被字典中的元素构成的所有构造方式字符串(中间由空格分割)。所以,我们只需要知道如果当前的字符串能分割,再拼接上后面的分割就行了。如果后面部分不能分割,应该返回的是空的vector,这样就不会产生新的结果字符串放入到res里。
Python代码如下:
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
res = []
memo = dict()
return self.dfs(s, res, wordDict, memo)
def dfs(self, s, res, wordDict, memo):
if s in memo: return memo[s]
if not s:
return [""]
res = []
for word in wordDict:
if s[:len(word)] != word: continue
for r in self.dfs(s[len(word):], res, wordDict, memo):
res.append(word + ("" if not r else " " + r))
memo[s] = res
return res
C++代码如下:
class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
set<string> wordset(wordDict.begin(), wordDict.end());
unordered_map<string, vector<string>> m;
return dfs(wordset, s, m);
}
private:
vector<string> dfs(set<string>& wordset, string s, unordered_map<string, vector<string>>& m) {
if (m.count(s)) return m[s];
if (s.empty()) return {""};
vector<string> res;
for (string word : wordset) {
if (s.substr(0, word.size()) != word) continue;
vector<string> remain = dfs(wordset, s.substr(word.size()), m);
for (string r : remain) {
res.push_back(word + (r.empty() ? "" : " ") + r);
}
}
return m[s] = res;
}
};
也可以不用一个新的函数,直接在原始的函数上进行操作。这时候就需要一个全局的字典。代码如下:
class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
if (m.count(s)) return m[s];
if (s.empty()) return {""};
vector<string> res;
for (string word : wordDict) {
if (s.substr(0, word.size()) != word) continue;
for (string r : wordBreak(s.substr(word.size()), wordDict)) {
res.push_back(word + (r.empty() ? "" : " ") + r);
}
}
return m[s] = res;
}
private:
unordered_map<string, vector<string>> m;
};
参考资料:http://www.cnblogs.com/grandyang/p/4576240.html
日期
2018 年 12 月 19 日 —— 感冒了,好难受
【LeetCode】140. Word Break II 解题报告(Python & C++)的更多相关文章
- LeetCode: Word Break II 解题报告
Word Break II Given a string s and a dictionary of words dict, add spaces in s to construct a senten ...
- [LeetCode] 140. Word Break II 单词拆分II
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add space ...
- Java for LeetCode 140 Word Break II
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each ...
- leetcode 140. Word Break II ----- java
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each ...
- Leetcode#140 Word Break II
原题地址 动态规划题 令s[i..j]表示下标从i到j的子串,它的所有分割情况用words[i]表示 假设s[0..i]的所有分割情况words[i]已知.则s[0..i+1]的分割情况words[i ...
- leetcode 139. Word Break 、140. Word Break II
139. Word Break 字符串能否通过划分成词典中的一个或多个单词. 使用动态规划,dp[i]表示当前以第i个位置(在字符串中实际上是i-1)结尾的字符串能否划分成词典中的单词. j表示的是以 ...
- 140. Word Break II(hard)
欢迎fork and star:Nowcoder-Repository-github 140. Word Break II 题目: Given a non-empty string s and a d ...
- 【LeetCode】140. Word Break II
Word Break II Given a string s and a dictionary of words dict, add spaces in s to construct a senten ...
- [Leetcode Week9]Word Break II
Word Break II 题解 题目来源:https://leetcode.com/problems/word-break-ii/description/ Description Given a n ...
随机推荐
- 金蝶EAS——登录某个数据中心门户时报错“获取用户相关信息失败!请查看服务器日志,并确认是否数据库设置错误或者版本不匹配!”
登录服务器后台,查看金蝶BOS控制台,选择数据中心中的目标数据中心,点击测试连接,提示报错如下: 说明是数据库问题,需要登录数据库服务器去检查数据库.详细操作见:
- 6. Reverse Linked List 逆转单链表
逆转单链表,比较简单,不细讲,扫描依次改变指针指向. class Solution { public: ListNode* reverseList(ListNode* head) { if(head= ...
- C语言中的位段----解析
有些信息在存储时,并不需要占用一个完整的字节, 而只需占几个或一个二进制位. 例如在存放一个开关量时,只有0和1 两种状态, 用一位二进位即可. 为了节省存储空间并使处理简便,C语言又提供了一种数据结 ...
- Hadoop运行jar包报错java.lang.Exception: java.lang.ArrayIndexOutOfBoundsException: 1
错误信息: java.lang.Exception: java.lang.ArrayIndexOutOfBoundsException: 1 at org.apache.hadoop.mapre ...
- C++福尔摩斯的约会
这道题的要求总结如下: 1.DAY 星期 大写字母:A B C D E F G2.HH 时 数字+大写字母 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M ...
- LeetCode1579题——圆圈中最后剩下的数字
1.题目描述:0,1,,n-1这n个数字排成一个圆圈,从数字0开始,每次从这个圆圈里删除第m个数字.求出这个圆圈里剩下的最后一个数字.例如,0.1.2.3.4这5个数字组成一个圆圈,从数字0开始每次删 ...
- Linux基础命令---mput上传ftp文件
mput 使用lftp登录ftp服务器之后,可以使用put指令将文件上传到服务器.mput指令可以使用通配符,而put指令则不可以. 1.语法 mput [-c] [-d] [-a] ...
- 【Linux】【Services】【MessageQueue】搭建高可用rabbitMQ
1. 简介 1.1. 官方网站: https://www.rabbitmq.com/ 1.2. 配置文档:https://docs.openstack.org/ha-guide/shared-mess ...
- 【spring AOP】@Pointcut的12种用法
@Pointcut用来标注在方法上来定义切入点. 使用格式:@ 注解(value="表达标签 (表达式格式)").如:@Pointcut("execution(* com ...
- SQL错误总结
ORA-00918: column ambiguously defined 异常原因: select 查询的字段在from的两张表中都存在,导致数据库无法区别需要查询的字段来自于哪张表 以下是例子 s ...