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. 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"]
.
对于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(单词切分)的更多相关文章
- [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 ...
- 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 139. Word Break 、140. Word Break II
139. Word Break 字符串能否通过划分成词典中的一个或多个单词. 使用动态规划,dp[i]表示当前以第i个位置(在字符串中实际上是i-1)结尾的字符串能否划分成词典中的单词. j表示的是以 ...
- 【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 ...
- 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 ...
- 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 ...
- 【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 ...
- 【Word Break II】cpp
题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where e ...
随机推荐
- Python与JavaWeb的第一次碰撞
在Python中向服务器提交一个表单数据看起来是很容易的,但是这次经历着实让我记忆深刻,借此也为了警醒同样遇到了这样问题的你们. 要做什么? 使用Python的urllib2模块提交表单数据,并在服务 ...
- 【翻译】Ext JS 6.2 早期访问版本发布
原文:Announcing Ext JS 6.2 Early Access 非常开心,Sencha Ext JS 6.2早期访问版本今天发布了.早期访问版本的主要目的是为了让大家进行测试并评估Ext ...
- javaRMI详解
前几天在阿里内推一面的时候,面试官问到了一个关于java中RMI(Remote Method Invocation)的问题,当时感觉自己回答的还比较好,他比较满意,但那是因为他问的比较浅,所以自己看了 ...
- 【一天一道LeetCode】#103. Binary Tree Zigzag Level Order Traversal
一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 来源: htt ...
- React 语法之let和const命令
let命令 基本用法 ES6新增了let命令,用来声明变量.它的用法类似于var,但是所声明的变量,只在let命令所在的代码块内有效. { let a = 10; var b = 1; } a // ...
- equals()与hashCode()方法协作约定
翻译人员: 铁锚 翻译时间: 2013年11月15日 原文链接: Java equals() and hashCode() Contract 图1 Java所有对象的超类 java.lang.Obje ...
- [WinForm]dataGridView自定动态设定序号列框
你可以在数据绑定或者行数有很大变化时测量一下DataGridView最大行数的行数的宽度然后在绘制代码如下 SolidBrush solidBrush; StringFormat stringForm ...
- python import自己编写的模块:import json和simplejson
python import的模块都是库里面的,而自己的模块也可以添加 比如python的json处理,库里没有json文件,import json不行. 网上大部分人告诉你处理json用 dumps和 ...
- 学习pthreads,使用条件变量进行多线程之间的同步
条件变量提供另一种多线程同步的方法.互斥量通过控制对共享数据的访问来同步任务.条件变量可以根据数据的值来同步任务.条件变量是当一个事件发生时发送信号的信号量.一旦事件发生,可能会有多个线程在等待信号, ...
- 【翻译】在Ext JS 5应用程序中如何使用路由
原文:How to Use Routing in Your Ext JS 5 Apps 简介 Ext JS 5是一个重要的发布版本,它提供了许多新特性来创建丰富的.企业级的Web应用程序.MVVM和双 ...