Word Break II 求把字符串拆分为字典里的单词的所有方案 @LeetCode

153 篇文章 0 订阅
148 篇文章 69 订阅

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

public class Solution {
public List<String> wordBreak(String s, Set<String> dict) {
List<String> list = new ArrayList<String>();
List<String> ret = new ArrayList<String>();
rec(s, dict, list, ret);
return ret;
}

public void rec(String s, Set<String> dict, List<String> list, List<String> ret) {
if(!isBreak(s, dict)){  // test before run to avoid TLE
return;
}
if(s.length() == 0) {
String concat = "";
for(int i=0; i<list.size(); i++) {
concat += list.get(i);
if(i != list.size()-1) {
concat += " ";
}
}
return;
}

for(String cur : dict) {
if(cur.length() > s.length()) {     // avoid out of boundary
continue;
}
String substr = s.substring(0, cur.length());
if(substr.equals(cur)) {
rec(s.substring(cur.length()), dict, list, ret);
list.remove(list.size()-1);
}
}
}

public boolean isBreak(String s, Set<String> dict) {
boolean[] canBreak = new boolean[s.length()+1];
canBreak[0] = true;

for(int i=1; i<=s.length(); i++) {
boolean flag = false;
for(int j=0; j<i; j++) {
if(canBreak[j] && dict.contains(s.substring(j,i))) {
flag = true;
break;
}
}
canBreak[i] = flag;
}
return canBreak[s.length()];
}
}

• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 3
评论
01-20 718
12-23 4896

“相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。