您的位置:首页 > 其它

LeetCode Word Break II

2015-09-13 01:40 232 查看
原题链接在这里:https://leetcode.com/problems/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"]
.

题解:

本题是Word Break的进阶题,要返回所有wordbreak的结果。

本题参照了这篇帖子:/article/4896867.html

首先更具isWordBreak判断是否能拆,这一步不能省略。若能拆看从头到尾走,找到了一个wordDict里包含的字符串,然后从后一个点就用递归方法调用helper, 递归的stop condition是能走到正好结尾,否则跳出for loop, res不变。

Note: helper的for loop中若wordDict包含当前sb.toString(), 应该建立一个新的string, newString, 它相当于一个copy, 因为回朔到这点时,str应该回到最开始的时候,若不用这个copy当回到这点时str可能已经不是最开始的状态。

AC Java:

public class Solution {
public List<String> wordBreak(String s, Set<String> wordDict) {
List<String> res = new ArrayList<String>();
if(s == null || s.length() == 0){
return res;
}

if(isBreak(s,wordDict)){
helper(s,wordDict,0,"",res);
}
return res;
}

private void helper(String s, Set<String> wordDict, int start, String item, List<String> res){
if(start == s.length()){
res.add(item);
return;
}
StringBuilder sb = new StringBuilder();
for(int i = start; i<s.length(); i++){
sb.append(s.charAt(i));
if(wordDict.contains(sb.toString())){
String str = "";    //这里必须要做复制
if(item.length() == 0){
str = sb.toString();
}else{
str = item + " " + sb.toString();
}
helper(s,wordDict,i+1,str,res);
}
}
}

private boolean isBreak(String s, Set<String> wordDict){
if(s == null || s.length() == 0){
return true;
}
boolean [] res = new boolean[s.length()+1];
res[0] = true;
for(int i = 1; i<res.length; i++){
StringBuilder sb = new StringBuilder(s.substring(0,i));
for(int j = 0; j<i; j++){
if(res[j] && wordDict.contains(sb.toString())){
res[i] = true;
}
sb.deleteCharAt(0);
}
}
return res[res.length-1];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: