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的更多相关文章

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

  2. Word Break II -- leetcode

    Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each ...

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

  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. [Leetcode Week9]Word Break II

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

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

  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 139. Word Break 、140. Word Break II

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

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

随机推荐

  1. PHP安全编程:会话数据注入 比会话劫持更强大的攻击(转)

    一个与会话暴露类似的问题是会话注入.此类攻击是基于你的WEB服务器除了对会话存储目录有读取权限外,还有写入权限.因此,存在着编写一段允许其他用户添加,编辑或删除会话的脚本的可能.下例显示了一个允许用户 ...

  2. 前端工具之WebPack解密之背景

    请注意,这是一篇站在完全新手的角度上来写的文章.可能你是一个后端人员想了解前端工具的使用和概念;也可能你是一个前端小菜(还在DIV+CSS的世界里挣扎着).本文比较适合那些以前完全没有接触过WebPa ...

  3. java的通信机制

    通信机制无非就那几种:http访问.socket访问: http又分为:jsp.servlet.html,用的就是get和post方法 socket则可分为:tcp或者udp方式 从以上内容又衍生出其 ...

  4. GDataXML的配置和使用

    1.下载链接:http://code.google.com/p/gdata-objectivec-client/downloads/list下载“gdata-objective-c client li ...

  5. 什么是AAC音频格式 AAC-LC 和 AAC-HE的区别是什么

    Advanced Audio Coding(高级音频解码),是一种由MPEG-4标准定义的有损音频压缩格式,由Fraunhofer发展,Dolby, Sony和AT&T是主要的贡献者. 在使用 ...

  6. GIT学习(一)-->Git产生的历史原因

    首先要说:Git是目前世界上最先进的分布式版本控制系统(没有之一). git的作者:Linus,林纳斯(下图就是,先膜拜一下,因为成就可不止这一点) 他是为何要写git的呢?话说 Linus虽然创建了 ...

  7. Datables wrning(table id='example'):Cannot reinitialise DataTable.

    出现的问题如下所示: Datables wrning(table id='example' Datables object for this table,please pass eithser no ...

  8. My.Ioc 代码示例——使用条件绑定和元数据(可选)构建插件树

    本文旨在通过创建一棵插件树来演示条件绑定和元数据的用法. 说“插件树”也许不大妥当,因为在一般观念中,谈到插件树,我们很容易会想到 Winform/Wpf 中的菜单.举例来说,如果要在 Winform ...

  9. (转)PHP的ereg()与eregi()的不同及相同点。对比

    ereg() 字符串比对解析. 语法: int ereg(string pattern, string string, array [regs]); 返回值: 整数/数组 函数种类: 资料处理 内容说 ...

  10. scrolView

    禁止UIScrollView垂直方向滚动,只允许水平方向滚动 scrollview.contentSize =  CGSizeMake(长度, 0); 禁止UIScrollView水平方向滚动,只允许 ...