Word Break

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

解法1,递归,超时

有两种递归方式,一种是按s的子串递归,一种是按集合dict递归

第一种:

 public boolean wordBreak(String s, Set<String> dict) {
if(dict.contains(s)){
return true;
}
boolean flag = false;
for(int i=1;i<s.length();i++){
if(dict.contains(s.substring(0,i))){
flag = wordBreak(s.substring(i),dict);
}
}
return flag;
}

第二种:

 public boolean wordBreak(String s, Set<String> dict) {
if(dict.contains(s)||s.equals("")){
return true;
}
boolean flag = false;
for(String now:dict){
for(int i = 0;i<s.length()-now.length();i++){
if(s.substring(i, i+now.length()).equals(now)){
flag = wordBreak(s.substring(0,i), dict)&&wordBreak(s.substring(i+now.length()), dict);
if(flag){
return true;
}
}
}
}
return flag;
}

解法2:动态规划

设flag[]为boolean数组,flag[i]表示s.substring(0,i)是否满足wordbreak,因此有状态转移方程为:

flag[n] = ∑flag[i]&&s.substring(i,n)   (i 取值为从1到n-1),有代码如下:

 public boolean wordBreak(String s, Set<String> dict) {
boolean flag[] = new boolean[s.length()+1];
flag[0] = true;
for(int i=1;i<=s.length();i++){
for(int j=0;j<i;j++){
flag[i] = flag[i] || (flag[j]&&dict.contains(s.substring(j, i)));
if(flag[i]){
continue;
}
}
}
return flag[s.length()];
}

递归的复杂度为O(2^n),动态规划的复杂度为O(n^2)

个人感觉,动态规划版本就是递归中第一种解法的非递归版,递归是自顶向下计算,动态规划是自底向上计算。

Word Break II

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"].

做法与上面相似,boolean数组变成list<Integer>的数组,记录当前位可以从前面哪些位得出,先自底向上生成数组,然后自顶向下构造字符串,直接贴代码:

 private List<String> result = new ArrayList<String>();
public List<String> wordBreak(String s, Set<String> dict) {
List<List<Integer>> flag = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
temp.add(0);
flag.add(temp);
for (int i = 1; i <= s.length(); i++) {
temp = new ArrayList<Integer>();
for (int j = 0; j < i; j++) {
if (dict.contains(s.substring(j, i)) && flag.get(j).size() > 0) {
temp.add(j);
}
}
flag.add(temp);
}
genList(flag, s, "", flag.get(flag.size() - 1), flag.size() - 1);
return result;
} private void genList(List<List<Integer>> flag, String source, String now,
List<Integer> list, int pos) {
// TODO Auto-generated method stub
if (pos == 0) {
result.add(now);
return;
}
for (Integer i : list) {
String temp = "";
if (now.equals("")) {
temp = source.substring(i, pos); } else {
temp = source.substring(i, pos) + " " + now;
}
genList(flag, source, temp, flag.get(i), i.intValue());
}
}

Word Break I II的更多相关文章

  1. LeetCode: Word Break I && II

    I title: https://leetcode.com/problems/word-break/ Given a string s and a dictionary of words dict, ...

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

  4. LeetCode:Word Break II(DP)

    题目地址:请戳我 这一题在leetcode前面一道题word break 的基础上用数组保存前驱路径,然后在前驱路径上用DFS可以构造所有解.但是要注意的是动态规划中要去掉前一道题的一些约束条件(具体 ...

  5. 140. Word Break II

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

  6. [LeetCode] Word Break II 解题思路

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

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

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

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

随机推荐

  1. Java宝典(一)

    -switch语句能作用在byte上,能否作用在long上,能否作用在String上? -在switch(expr1)中,expr1只能是一个整数表达式或者枚举常量,整数表达式可以是int基本类型或I ...

  2. matlab学习

    1.将一个图片嵌入一张图里,去除黑边 clc clear close all I = imread('qiegray.jpg'); I = rgb2gray(I); I = double(I); I1 ...

  3. POJ 1300 欧拉通路&欧拉回路

    系统的学习一遍图论!从这篇博客开始! 先介绍一些概念. 无向图: G为连通的无向图,称经过G的每条边一次并且仅一次的路径为欧拉通路. 如果欧拉通路是回路(起点和终点相同),则称此回路为欧拉回路. 具有 ...

  4. mac下显示隐藏文件

    一.在终端中 ls -a就可以查看隐藏文件. 显示和隐藏的命令例如以下: 显示:defaults write com.apple.finder AppleShowAllFiles -bool true ...

  5. 数据分析系统DIY3/3:本地64位WIN7+matlab 2012b訪问VMware CentOS7+MariaDB

    数据分析系统DIY中要完毕的三个任务. 一.用VMware装64位CentOS.数据库服务端用CentOS自带的就好. 二.数据採集与预处理用Dev-C++编程解决. 三.用本地Win7 64上的MA ...

  6. [Javascript] How to write a Javascript libarary

    Create package.json file //npm settings npm set init-author-name 'username' npm set init-author-emai ...

  7. IOS中对图片进行重绘处理的方法总结

    一.CGImageRef是什么 CGImageRef是定义在QuartzCore框架中的一个结构体指针,用C语言编写.在CGImage.h文件中,我们可以看到下面的定义: ? 1 typedef st ...

  8. 该如何关闭thinkphp的缓存呢?有下面几种方法可参考:

    该如何关闭thinkphp的缓存呢?有下面几种方法可参考: (1)在配置文件中关闭缓存 在你的配置文件config.php文件中加上如下两句:   复制代码代码如下: 'TMPL_CACHE_ON'  ...

  9. android——屏幕适配大全(转载)

    http://my.oschina.net/u/2008084/blog/496161 一.适配可行性 早在Android设计之初就考虑到了这一点,为了让app适应标准or山寨屏幕,google已经有 ...

  10. Oralce 按分隔符把一列转成多行

    1.前言 最近因项目需求,需要把员工的工作组返回给前台,但是数据库是把员工的工作组Id,都存在一个字段内了(以“逗号”分隔),而这样不符合前台的需要,他们需要一行,一行的数据.如: 数据库: user ...