Word Break II——LeetCode
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
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"].
题目大意就是:给一个string,一个词典,把这个string根据词典构建出所有可能的组合。
我的解法就是预处理+DFS+剪枝。
1、首先用一个breakFlag数组,记录string中的各个位置为结尾是否是合法的分词末尾,以上面的样例来说,c,a都是不合法的分词结尾,t,s都是合法的分词结尾。
2、然后用DFS来搜全部可能的组合,如果最后正好分完这个string,说明是合法的分词方法,组合成句子然后添加到结果List中,有个小优化就是可以先把字典里的单词的长度放入一个array,分词的时候只需要遍历这个array就可以,比如上面的字典里单词长度只有{3,4}组成一个array,只需要遍历cat cats就可以继续往后遍历了。
Talk is cheap>>
package leetcode; import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set; public class WordBreakII { public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("cat");
set.add("cats");
set.add("and");
set.add("sand");
set.add("dog");
new WordBreakII().wordBreak("catsanddog", set);
} Set<Integer> lenArray = new HashSet<>();
boolean[] breakFlag; public List<String> wordBreak(String s, Set<String> dict) {
List<String> res = new ArrayList<>();
for (String next : dict) {
lenArray.add(next.length());
}
breakFlag = new boolean[s.length() + 1];
breakFlag[0] = true;
for (int i = 0; i < s.length(); i++) {
if (breakFlag[i]) {
for (int j = 0; i + j < s.length() + 1; j++) {
if (dict.contains(s.substring(i, i + j)))
breakFlag[i + j] = true;
}
}
}
if (breakFlag[s.length()])
dfs(s, "", dict, res, s.length());
return res;
} public void dfs(String src, String tmp, Set<String> dict, List<String> res, int length) {
if (length < 0) {
return;
}
if (length == 0) {
System.out.println(tmp.substring(0, tmp.length() - 1));
res.add(tmp.substring(0, tmp.length() - 1));
return;
}
for (int len : lenArray) {
int left = src.length() - len;
if (left < 0)
break;
String t = src.substring(left, src.length());
if (breakFlag[length] && dict.contains(t)) {
dfs(src.substring(0, left), t + " " + tmp, dict, res, length - len);
}
}
} }
Word Break II——LeetCode的更多相关文章
- Word Break II leetcode java
题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where e ...
- Word Break II -- leetcode
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each ...
- 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: 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 ...
- 【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】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 139. Word Break 、140. Word Break II
139. Word Break 字符串能否通过划分成词典中的一个或多个单词. 使用动态规划,dp[i]表示当前以第i个位置(在字符串中实际上是i-1)结尾的字符串能否划分成词典中的单词. j表示的是以 ...
- 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 ...
随机推荐
- 【开源java游戏框架libgdx专题】-02-Eclipse Gradle 环境安装
创建eclipse开发环境 Eclipse 4.5 Help -> install newsoftware 填上下载地址(Eclipse 4.5及以上版本): http://dist.sprin ...
- Electron
跨平台桌面app开发 Appjs hex nwjs electron 官网:http://electron.atom.io/ 中文文档:https://github.com/atom/electron ...
- java 类处理工具
public class ClassUtils { private static final Logger LOGGER = LoggerFactory.getLogger(ClassUtils.cl ...
- mysql查看binlog日志
1.语法:(用于在二进制日志中显示事件.如果您不指定’log_name’,则显示第一个二进制日志.LIMIT子句和SELECT语句具有相同的语法.) show binlog events [IN 'l ...
- asp.net 从客户端中检测到有潜在危险的 Request.Form 值错误解
从客户端(ftbContent="<P><A href="http://l...")中检测到有潜在危险的 Request.Form 值. 说明: 请求验 ...
- XlFileFormat
-----转载:http://hi.baidu.com/liu_haitao/item/900ddb38979188c22f8ec26e 18 XlFileFormat.xlAddIn Microso ...
- tinkphp URL重写,支持伪静态
通常的URL里面含有index.php,为了达到更好的SEO效果可能需要去掉URL里面的index.php ,通过URL重写的方式可以达到这种效果,通常需要服务器开启URL_REWRITE模块才能支持 ...
- 使用EditText搜索listview里面的内容,实现Listview跟随变动的情况
1.布局的XML文件里面添加EditText控件(省略)控件id=mSearch ListView的id=admin_lv; 2.一.获取ListView展示的数据(通过适配器获取) 二.这个是我要说 ...
- windows下安装CI框架
CI框架是一个非常流行的 mvc框架, CI框架如何安装和使用,在CI中文网已经讲的比较详细了 ,这里记录下几个需要注意的地方. 一. index.php问题 把压缩包下载解压到项目根目录即可运行里面 ...
- restrict和volatile的作用
每当看到这两个关键字,我都无比的头痛啊,当时看到理解了一下就明白了,但是在此遇到就忘记是怎么用的了,今天就索性写一写吧,好记性不如烂笔头呗,烂笔头不如存在网上. restrict是c99引入的,关键字 ...