LeetCode笔记:140. Word Break II
题目描述


给定一个非空的字符串s,一个非空的字符串list作为字典。通过在s中添加空格可以将s变为由list中的word表示的句子,要求返回所有可能组成的句子。设定list中的word不重复,且每一个word都可以重复使用。
算法一
先来一个暴力的方法,如下图所示:1)用一个currStr记录当前句子,初始为“”,两个指针start、end分别表示当前词word的起始和结束;2)如果word在list中则将其加入currStr中,start = end +1,否则end后移;3)重复 2)操作直到end超出s的范围。4)可以先计算list中最长word 的长度,作为end后移次数的长度限制。
这种算法存在需要对同一子字符串需要重复计算的情况,提交代码时显示Time Limit Exceeded

class Solution {
public static int maxLen = 0;
public List<String> wordBreak(String s, List<String> dict) {
List<String> res = new ArrayList<String>();
if(dict.size() == 0 || s == null || s.length() == 0) return res;
maxLen = getMaxLen(dict);
dfs(s, dict, 0, res);
return res;
}
public void dfs(String s, List<String> dict, int index, List<String> res){
if(index >= s.length()){
res.add(s.trim());
return;
}
for(int i=index+1; (i<=index + maxLen) && (i<=s.length()); i++){
String word = s.substring(index, i);
if(inDict(word, dict)){
String newStr = s.substring(0, i) + " " + s.substring(i, s.length());
dfs(newStr, dict, i+1, res);
}
}
}
public boolean inDict(String w, List<String> s){
for(String str : s){
if(str.equals(w)){
return true;
}
}
return false;
}
public int getMaxLen(List<String> s){
int max = 0;
for(String str:s){
max = max > str.length()?max : str.length();
}
return max;
}
}
算法二
算法一之所以会超时,原因是可能对同一个的子字符串重复计算。例如s = “abcdabccc”,list = {"ab", "cd", "abcd", "ccc"}。当currStr = “ab cd”时,要对剩余子字符串“abccc”计算一次,currStr = “abcd”时,还需要对“abccc”再进行一次计算。这就是所谓的子问题重复的情况了,因此可以用动态规划来解决问题。
用一个Map来存储子字符串和其对应的所有句子组合方式。但对某一个字符串s进行查询时:若Map中包含该字符串的组合方式,则直接返回;否则,对每一个位于s开头且包含于list中的word,计算其剩余子串的句子组合方式,将其与该单词组合成新的句子。
class Solution {
public List<String> wordBreak(String s, List<String> wordDict) {
if(s == null || wordDict == null) return null;
return helper(s, wordDict, new HashMap<String, List<String>>());
}
private List<String> helper(String s, List<String> wordDict,
HashMap<String, List<String>> dp){
if(dp.containsKey(s)) return dp.get(s);
List<String> res = new ArrayList<>();
if(s.length() == 0) {
res.add("");
dp.put("", res);
return res;
}
for(int i=0; i<wordDict.size(); i++) {
String word = wordDict.get(i);
if(s.startsWith(word)) {
List<String> restRes = helper(s.substring(word.length(), s.length()),
wordDict, dp);
if(restRes.size() != 0) {
for(String eleInRest : restRes) {
if(eleInRest.length() == 0) {
res.add(word);
}else{
res.add(word + " " + eleInRest);
}
}
}
}
}
dp.put(s, res);
return res;
}
}
LeetCode笔记:140. Word Break II的更多相关文章
- 【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】140. Word Break II 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归求解 日期 题目地址:https://leetc ...
- 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 单词拆分II
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add space ...
- 140. Word Break II
题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where e ...
- 【LeetCode OJ】Word Break II
Problem link: http://oj.leetcode.com/problems/word-break-ii/ This problem is some extension of the w ...
- 139. Word Break 以及 140.Word Break II
139. Word Break Given a non-empty string s and a dictionary wordDict containing a list of non-empty ...
- leetcode@ [139/140] Word Break & Word Break II
https://leetcode.com/problems/word-break/ Given a string s and a dictionary of words dict, determine ...
随机推荐
- Maven - <Profile>详解
转载自:https://www.cnblogs.com/wxgblogs/p/6696229.html Profile能让你为一个特殊的环境自定义一个特殊的构建:profile使得不同环境间构建的可移 ...
- 帆软报表(finereport)间格运算常用公式
1.1在C3(占比)单元格中直接使用占比公式:=PROPORTION(B3):占比:当前值占总值的比例 1.2 计组内占比注:C2[!0]{A2=$A2},表示C2扩展出来地区相同的单元格.sum(C ...
- 帆软报表(finereport)实现自动滚屏效果
例如Demo:IOS平台年度数据报表. 展示内容丰富,一个页面中存在多个图表.内容,超出了浏览器窗口的大小导致内容展示不全. 为了能够预览这个报表的全部内容,可以使用JS滚屏效果来实现. 操作步骤: ...
- js 本地缓存localStorage
.localStorage - 没有时间限制的数据存储 ,,]; localStorage.setItem("stor",arr); console.log(localStorag ...
- UiAutomator2.0 - 控件实现点击操作原理
目录 一.UiObject 二.UiObject2 穿梭各大技术博客网站,每天都能看到一些的新的技术.突然感觉UiAutomator 2.0相对于现在来说已经是个很久远的东西了ε=(´ο`*))).写 ...
- Oracle 正则表达式 分割字符串
inData='12345|张三|男' SELECT REGEXP_SUBSTR (inData, '[^|]+', 1,1) into 用户ID FROM DUAL;SELECT REGEXP_SU ...
- 「JOISC 2017 Day 3」幽深府邸
题解: 和hnoi2018day2t1基本一样 我想了半小时想出了一个很麻烦的做法 写了之后发现假掉了 刚开始想的是 先预处理出每个门要打开至少要在左边的哪个点$L[]$,右边的哪个点$R[]$ 对每 ...
- 《连载 | 物联网框架ServerSuperIO教程》- 16.集成OPC Server,及使用步骤。附:3.3 发布与版本更新说明。
1.C#跨平台物联网通讯框架ServerSuperIO(SSIO)介绍 <连载 | 物联网框架ServerSuperIO教程>1.4种通讯模式机制. <连载 | 物联网框架Serve ...
- 实现upnp ssdp来查找局域网内的其他节点
upnp协议常用于一些智能家居产品中,这些产品连上家里局域网后,用同样连入家中局域网的手机就能很快检测到此产品了.在区块链技术中,upnp也被应用于寻找同一局域网内的其他节点. 关于upnp的具体描述 ...
- python分支——if
单分支判断 age = 16 if age >= 18: 判断语句,判断age是否大于等于18,注意if后面要加空格,条件写完后要加: print("你已经成年") prin ...