题目描述

给定一个非空的字符串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的更多相关文章

  1. 【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 ...

  2. 【LeetCode】140. Word Break II 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归求解 日期 题目地址:https://leetc ...

  3. leetcode 139. Word Break 、140. Word Break II

    139. Word Break 字符串能否通过划分成词典中的一个或多个单词. 使用动态规划,dp[i]表示当前以第i个位置(在字符串中实际上是i-1)结尾的字符串能否划分成词典中的单词. j表示的是以 ...

  4. 140. Word Break II(hard)

    欢迎fork and star:Nowcoder-Repository-github 140. Word Break II 题目: Given a non-empty string s and a d ...

  5. [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 ...

  6. 140. Word Break II

    题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where e ...

  7. 【LeetCode OJ】Word Break II

    Problem link: http://oj.leetcode.com/problems/word-break-ii/ This problem is some extension of the w ...

  8. 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  ...

  9. 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 ...

随机推荐

  1. 2018-2019-2 20165325《网络对抗技术》Exp0 Kali安装 Week1

    2018-2019-2 20165325<网络对抗技术>Exp0 Kali安装 Week1 一.安装kali VMware上学期已经有了,主要是下载Kali-Linux-2019.1-vm ...

  2. 增加swap分区

    起因:开发人员说tomcat关闭了,然后我排查了下,发现内存耗尽,然后临时用swap分区,以供当前运行的程序使用. 先用free -h查看一下swap的大小 1.添加swap分区 使用dd命令创建/h ...

  3. ftp和mysql数据库结合使用

    问题描述: 看下 1.1.1.1 的ftp为什么连不上 报错的信息: 'ftpServer' => '1.1.1.1', // FTP服务器地址 ', 'ftpUsername' => ' ...

  4. 【Python】Flask中@wraps的使用

    先说总结,白话来讲,@wraps相当于是装饰器的装饰器. python内置的方法使用解释,看起很复杂的样子┓( ´∀` )┏ def wraps(wrapped, assigned = WRAPPER ...

  5. 浅谈《Linux就该这么学》

    就在去年十月份的时候,偶尔在Linux技术群了看到别人分享的<Linux就该这么学>,好奇的就点进去看看,当时看完首页,突然发现刘遄老师说到心坎里去了,于是就仔细看了看红帽认证的讲解以及后 ...

  6. 20175226 2018-2019-2《java程序设计》结对编程-四则运算(第二周-阶段总结)

    需求分析(描述自己对需求的理解,以及后续扩展的可能性) 实现一个命令行程序,要求: 自动生成小学四则运算题目(加,减,乘,除) 支持整数 支持多运算符(比如生成包含100个运算符的题目) 支持真分数 ...

  7. Django报错:OSError: raw write() returned invalid length 4 (should have been between 0 and 2)

    在使用Django时Django报错:Django报错:OSError: raw write() returned invalid length 4 (should have been between ...

  8. Linux下创建共享文件夹

    1,查看ip 地址 ifconifg: 2,查看是否安装samba服务器,rpm -qa | grep samba: 3,如果有该服务器,启动 service smb start,否则进行安装 yum ...

  9. HihoCoder - 1038 01背包 动态规划

    #1038 : 01背包 时间限制:20000ms 单点时限:1000ms 内存限制:256MB 描述 且说上一周的故事里,小Hi和小Ho费劲心思终于拿到了茫茫多的奖券!而现在,终于到了小Ho领取奖励 ...

  10. 2018-2019-2 网络对抗技术 20165206 Exp2 后门原理与实践

    - 2018-2019-2 网络对抗技术 20165206 Exp2 后门原理与实践 - 实验任务 (1)使用netcat获取主机操作Shell,cron启动 (0.5分) (2)使用socat获取主 ...