Question:

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

----------------------------------------------

Solution:

dfs.

但是需要注意的是,在dfs之前,需要判断这个string能不能被这个dictionary分割(Word Break)。

 public class Solution {
public List<String> wordBreak(String s, Set<String> dict) {
List<String> result=new ArrayList<String>();
if(!wordBreakPossible(s,dict)) return result;
dfs(s,dict,result,"",0);
return result;
} private void dfs(String s, Set<String> dict, List<String> result,String temp, int start) {
// TODO Auto-generated method stub
if(start==s.length())
result.add(temp);
else{
if(start!=0)
temp+=" ";
for(int i=start;i<s.length();i++){
String word=s.substring(start, i+1);
if(dict.contains(word))
dfs(s,dict,result,temp+word,i+1);
}
}
} private boolean wordBreakPossible(String s, Set<String> dict) {
// TODO Auto-generated method stub
boolean[] state=new boolean[s.length()+1];
state[0]=true;
for(int i=1;i<=s.length();i++){
for(int j=i-1;j>=0;j--){
if(state[j]&&dict.contains(s.substring(j, i))){
state[i]=true;
break;
} }
}
return state[s.length()];
}
}

----------------------------------------------------------------------

20150221:

又忘了在dfs之前去判断这个string是否可以被这个dictionary分割:

导致出现了TLE:

Last executed input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]
 public class Solution {
public List<String> wordBreak(String s, Set<String> dict) { List<String> res=new ArrayList<String>();
if(s==null||s.length()==0||dict==null||dict.size()==0)
return res;
if(!wordBreakPossible(s,dict)) return res;
dfs(res,s,dict,"");
return res;
}
public void dfs(List<String> res,String s,Set<String> dict,String temp){
if(s.length()==0){ res.add(temp.trim());
return;
}
for(int i=1;i<=s.length();++i){
String t=s.substring(0,i);
if(dict.contains(t)){
dfs(res,s.substring(i),dict,temp+" "+t);
}else{
continue;
}
}
}
private boolean wordBreakPossible(String s, Set<String> dict) {
// TODO Auto-generated method stub
boolean[] state=new boolean[s.length()+1];
state[0]=true;
for(int i=1;i<=s.length();i++){
for(int j=i-1;j>=0;j--){
if(state[j]&&dict.contains(s.substring(j, i))){
state[i]=true;
break;
} }
}
return state[s.length()];
}
}

[Leetcode] Word BreakII的更多相关文章

  1. LeetCode:Word Ladder I II

    其他LeetCode题目欢迎访问:LeetCode结题报告索引 LeetCode:Word Ladder Given two words (start and end), and a dictiona ...

  2. [leetcode]Word Ladder II @ Python

    [leetcode]Word Ladder II @ Python 原题地址:http://oj.leetcode.com/problems/word-ladder-ii/ 参考文献:http://b ...

  3. [LeetCode] Word Squares 单词平方

    Given a set of words (without duplicates), find all word squares you can build from them. A sequence ...

  4. [LeetCode] Word Pattern II 词语模式之二

    Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...

  5. [LeetCode] Word Pattern 词语模式

    Given a pattern and a string str, find if str follows the same pattern. Examples: pattern = "ab ...

  6. [LeetCode] Word Search II 词语搜索之二

    Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...

  7. [LeetCode] Word Frequency 单词频率

    Write a bash script to calculate the frequency of each word in a text file words.txt. For simplicity ...

  8. [LeetCode] Word Break II 拆分词句之二

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

  9. [LeetCode] Word Break 拆分词句

    Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa ...

随机推荐

  1. 菜鸟学Linux命令:tar命令 压缩与解压缩

    tar命令可以为linux的文件和目录创建档案.利用tar,可以为某一特定文件创建档案(备份文件),也可以在档案中改变文件,或者向档案中加入新的文件. tar最初被用来在磁带上创建档案,现在,用户可以 ...

  2. PHP获取远程图片并调整图像大小(转)

    <?php /** * *函数:调整图片尺寸或生成缩略图 *修改:2013-2-15 *返回:True/False *参数: * $Image 需要调整的图片(含路径) * $Dw=450 调整 ...

  3. php获取一维,二维数组长度的方法(有实例)

    在php中获取数组长度方法很简单,php为我们提供了两个函数可以计算一维数组长度,如count,sizeof都可以直接统计数组长度哦,下面我们来看几个实例吧.php如何获取数组的长度,使用php函数c ...

  4. 学习一下《JavaEE开发的颠覆者 Spring Boot实战 》

    SPRING,绕不过去的.

  5. Ubuntu下安装Nginx

    转载自:http://www.cnblogs.com/skynet/p/4146083.html 1.Nginx安装 我使用的环境是64位 Ubuntu 14.04, Nginx是Nginx 1.10 ...

  6. mysql编译时报的一个警告warning: type-punning to incomplete type might break strict-aliasing rules,可能是bug

    cmake的时候报了一个警告: /softdb/mysql-5.5.37/storage/innobase/handler/ha_innodb.cc:11870: warning: type-punn ...

  7. 直接拿来用!最火的Android开源项目(完结篇)(转)

    摘要:截至目前,在GitHub“最受欢迎的开源项目”系列文章中我们已介绍了40个Android开源项目,对于如此众多的项目,你是Mark.和码友分享经验还是慨叹“活到老要学到老”?今天我们将继续介绍另 ...

  8. VisualStudio一打开工程就崩溃-重打开output显示We were unable to automatically populate your Visual Studio Online accounts.

    and this method exactly effected on me

  9. SQLServer 维护脚本分享(10)索引

    --可添加索引的字段 migs.user_seeks,migs.avg_total_user_cost,migs.avg_user_impact,migs.last_user_seek ,mid.st ...

  10. ROC曲线绘制

    ROC 曲线绘制 个人的浅显理解:1.ROC曲线必须是针对连续值输入的,通过选定不同的阈值而得到光滑而且连续的ROC曲线,故通常应用于Saliency算法评价中,因为可以选定0~255中任意的值进行阈 ...