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. You may assume the dictionary does not contain duplicate words.

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(动态规划)

对于brute force解法,代码比较简单,每次维护一个当前结果集,然后遍历剩下的所有子串,如果子串在字典中出现,则保存一下结果,并放入下一层递归剩下的字符。思路接近于我们在N-Queens这些NP问题中经常用到的套路。给个指针,前面部分在字典中,就将其添加到字符串后,然后递归计算后半部分。

public ArrayList<String> wordBreak(String s, Set<String> dict) {
ArrayList<String> res = new ArrayList<String>();
if(s==null || s.length()==0)
return res;
helper(s,dict,0,"",res);
return res;
}
//在s中,从start开始到最后的子串的切分。
private void helper(String s, Set<String> dict, int start, String item, ArrayList<String> res)
{
if(start>=s.length())
{
res.add(item);
return;
}
StringBuilder str = new StringBuilder();
for(int i=start;i<s.length();i++)
{
str.append(s.charAt(i)); //这里可以用substring(start,i+1)
if(dict.contains(str.toString())) //前面部分包含,则递归判断后面部分
{
        //将前面部分添加到字符串后面。这里使用新串,是为了返回进行遍历i+1的时候不用删除前面添加的内容
String newItem = item.length()>0?(item+" "+str.toString()):str.toString();
helper(s,dict,i+1,newItem,res);
}
}
}

上面这个代码是可以,但是会出现重复计算结果集。

为了加快DFS的速度,我们应该添加记忆,也就是说,算过的字符串不要再重复计算。举例子:
apple n feng
app len feng
如果存在以上2种划分,那么feng这个字符串会被反复计算,在这里至少计算了2次。我们使用一个Hashmap把对应字符串的解记下来,这样就能避免重复的计算。 否则这一道题目会超时。

class Solution {
public List<String> wordBreak(String s, List<String> wordDict) {
//使用map存放每个子串对应的所有结果集,这样防止出现重复计算导致超时。因为如上面dog,会计算两遍结果集
HashMap<String,List<String>> map=new HashMap<String,List<String>>();
if(s==null||s.length()==0||wordDict==null) return null;
return helper(map,s,wordDict);
}
//字符串str能够切分得到的结果集
public List<String> helper(HashMap<String,List<String>> map,String str,List<String> wordDict){
if(map.containsKey(str)){//该字符串的结果集已经有了
return map.get(str);
}
List<String> list=new ArrayList<>();//存放当前字符串的结果集
int len=str.length();
if(len==0){
list.add(""); //""在list中也占一个长度。
}else{
for(int i=1;i<=len;i++){
String sub=str.substring(0,i);
if(!wordDict.contains(sub)) continue;
//包含前面部分,这时求出后半部分的结果集。。如果i==len此时结果集中为""。长度为1.不是0
List<String> rightList=helper(map,str.substring(i,len),wordDict); if(rightList.size()==0) continue; for(String ss:rightList){
StringBuilder sb=new StringBuilder();
sb.append(sub);
if(i!=0&&i!=len){//i==len时,整个字符串在字典中,直接添加整个字符串就行,不需要空格,此时ss==""。
sb.append(" ");
}
sb.append(ss);
list.add(sb.toString());
} }
} map.put(str,list);
return list;
}
}

word break II(单词切分)的更多相关文章

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

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

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

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

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

  5. 17. Word Break && Word Break II

    Word Break Given a string s and a dictionary of words dict, determine if s can be segmented into a s ...

  6. LeetCode之“动态规划”:Word Break && Word Break II

     1. Word Break 题目链接 题目要求: Given a string s and a dictionary of words dict, determine if s can be seg ...

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

  8. [Leetcode Week9]Word Break II

    Word Break II 题解 题目来源:https://leetcode.com/problems/word-break-ii/description/ Description Given a n ...

  9. 【Word Break II】cpp

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

随机推荐

  1. (NO.00004)iOS实现打砖块游戏(十二):伸缩自如,我是如意金箍棒(上)!

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请告诉我,如果觉得不错请多多支持点赞.谢谢! hopy ;) 通用的星星类已经完成了,下面我们来实现具体的变长和缩短道具. 变 ...

  2. 【一天一道LeetCode】#217. Contains Duplicate

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...

  3. 精通CSS+DIV网页样式与布局--页面背景

    上篇博客,我们主要简单的总结了CSS的图片效果,我们这回来讲讲CSS如何对网页的背景进行设置,网页的背景是整个网页的重要组成部分,她直接决定了整个网页的风格和色调.这篇博客简单的总结一下如何用CSS来 ...

  4. 【Unity Shaders】Transparency —— 使用渲染队列进行深度排序

    本系列主要参考<Unity Shaders and Effects Cookbook>一书(感谢原书作者),同时会加上一点个人理解或拓展. 这里是本书所有的插图.这里是本书所需的代码和资源 ...

  5. 求解n皇后

    要求:在国际象棋上摆放n个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行.同一列或同一斜线上,问有多少种摆法 思路:很直观的想法就是在棋盘上一个一个皇后的摆,如果冲突,则摆放在另一个位置,直至 ...

  6. 一种公认提供toString的方法_JAVA核心技术卷轴Ⅰ

    从JAVA核心技术卷轴Ⅰ:基础知识中整理得到. import java.lang.reflect.AccessibleObject; import java.lang.reflect.Array; i ...

  7. 【转载】2015 Objective-C 三大新特性 | 干货

    Overview 自 WWDC 2015 推出和开源 Swift 2.0 后,大家对 Swift 的热情又一次高涨起来,在羡慕创业公司的朋友们大谈 Swift 新特性的同时,也有很多像我一样工作上依然 ...

  8. android studio2.0出现的gradle问题,instant Run即时运行不了.

    android studio 2.0出现的gradle问题: instant Run即时运行不了.经历了几乎9个preView版本的AS2.0,终于迎来了正式版,然而晴天我的霹雳,好不容易装好的2.0 ...

  9. HTML入门笔记

    HTML简介 HTML是做网页最基本的技术 1_由标签组件 2_在任何操作系统平台,只要有浏览器,都有执行HTML 3_浏览器中有HTML解析器 4_编辑HTML可以使用任何文本编辑工具,如记事本,建 ...

  10. MyEclipse 报错:Errors running builder 'DeploymentBuilder' on project '工程名'

    并没有更换MyEclipse版本,只是重新卸载了下,然后就报错误,参考了网上的文章 解决版本 .就是删除工程下部署文件