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 ...
随机推荐
- linux常用的内核镜像格式
linux常用的内核镜像格式 Linux内核有多种格式的镜像,包括vmlinux.Image.zImage等. 1. Linux内核镜像格式 1.1 vmlinux vmlinuz是可引导的. ...
- SDL2源代码分析1:初始化(SDL_Init())
===================================================== SDL源代码分析系列文章列表: SDL2源代码分析1:初始化(SDL_Init()) SDL ...
- 新手学python(2):C语言调用完成数据库操作
继续介绍本人的python学习过程.本节介绍如何利用python调用c代码.内容还是基于音乐信息提取的过程,架构如图一.Python调用c实现的功能是利用python访问c语言完成mysql数据库操作 ...
- Common Bit Tasks
1) If you XOR a bit with its own negated value, you will always get 1. Therefore thesolution to a ^ ...
- 中国电信中兴F460光猫破解及路由级联设置
http://blog.csdn.net/pipisorry/article/details/50636541 中国电信中兴F460光猫破解,获取超级密码,修改配置. 之前家里的宽带升级了,换成了光纤 ...
- 汉字转拼音的Oracle函数
前言: 最近处理一个特殊的问题,需要用到汉字自动转换拼音的功能. 解决: 在这里找了不少资料,都是有所缺陷,而且也好像很绕.其实是一个很简单的东东.后来还是自己写了一个函数获取.分享出来,给有需要的X ...
- 【翻译】如何创建Ext JS暗黑主题之二
原文:How to Create a Dark Ext JS Theme– Part 2 我已经展示了如何去开发一个精致的暗黑主题,看起来就像Spotify.在本文的第一部分,了解了Fashion.S ...
- 一个简易版本的lua debugger实现
introduction 工欲善其事,必先利其器.lua作为一门动态语言,虽然我已经习惯了使用print来进行代码调试,但是还是有很多童鞋觉得一款好用的调试器能更好的进行lua代码编写.所以在以前接手 ...
- #include <iostream>与#include <iostream.h>的区别
在新的C++标准中,生成新头文件的方法仅仅是将现有C++头文件名中的 .h 去掉.例如,<iostream.h> 变成了<iostream> ,<complex. ...
- maven中去掉单元测试的配置
如果是在命令行中去掉测试,可以在命令行中输入:mvn install -Dmaven.test.skip=true 在pom.xml <plugins> <plugin& ...