【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 ...
随机推荐
- mGWAS研究思路
mGWAS(metabolome-based genome-wide association studies)的研究方法和GWAS类似,只是将代谢物含量作为表型性状来与基因位点进行关联.但同时它也有自 ...
- Linux服务器I/O性能分析-3
一.通过脚本分析IO的读/写数量.最大延迟.延迟的分布情况.块大小及数量 #!/bin/sh # # File Name : count_io.sh # Time : 2020-07-29-11:24 ...
- mysql 不等于 符号写法
今天在写sql语句的时候,想确认下mysql的不等于运算符是用什么符号表示的 经过测试发现mysql中用<>与!=都是可以的,但sqlserver中不识别!=,所以建议用<> ...
- Flink 实践教程-进阶(2):复杂格式数据抽取
作者:腾讯云流计算 Oceanus 团队 流计算 Oceanus 简介 流计算 Oceanus 是大数据产品生态体系的实时化分析利器,是基于 Apache Flink 构建的具备一站开发.无缝连接.亚 ...
- Redis | 第10章 二进制数组、慢查询日志和监视器《Redis设计与实现》
目录 前言 1. 二进制位数组 1.1 位数组的表示 1.2 GETBIT 命令的实现 1.3 SETBIT 命令的实现 1.4 BITECOUNT 命令的实现 1.5 BITOP 命令的实现 2. ...
- c#图标、显示图表、图形、json echarts实例 数据封装【c#】
page: <%@ Control Language="C#" AutoEventWireup="true" CodeFile="Viewxxx ...
- js获取中国省市区,省市筛选、省市、省市筛选联动。【C#】【js】
<style type="text/css"> .labelhide { -webkit-box-shadow: 0px 1px 0px 0px #f3f3f3 !im ...
- iOS 客户端获取七牛上传token
一.官方参考文档: 1.上传策略http://developer.qiniu.com/article/developer/security/put-policy.html 2.上传凭证(即uptoke ...
- ehcache详解
Ehcache是现在最流行的纯Java开 源缓存框架,配置简单.结构清晰.功能强大,最初知道它,是从Hibernate的缓存开始的.网上中文的EhCache材料以简单介绍和配置方法居多, 如果你有这方 ...
- gen already exists but is not a source folder. Convert to a source folder or rename it 的解决办法
1. Right click on the project and go to "Properties" //鼠标右键点击项目,然后选中Properties 2. Select ...