Word Break II
约 1 分钟· 本文阅读 次
本页目录
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].
Solution
check before constructing the sentences.
Code
public class Solution {
public List<String> wordBreak(String s, Set<String> dict) {
List<String> res = new ArrayList<String>();
int n = s.length();
boolean[] canBreak = new boolean[n+1];
canBreak[n] = true;
for (int i = n - 1; i >= 0; --i) {
for (int j = i; j < n; ++j) {
if (dict.contains(s.substring(i,j+1)) && canBreak[j+1]) {
canBreak[i] = true;
break;
}
}
}
if (canBreak[0] == false) return res;
wordBreakRe(s, dict, "", 0, res);
return res;
}
public void wordBreakRe(String s, Set<String> dict, String path, int start, List<String> res) {
if (start == s.length()) {
res.add(path);
return;
}
if (path.length() != 0) path = path + " ";
for (int i = start; i < s.length(); ++i) {
String word = s.substring(start, i + 1);
if (dict.contains(word) == false) continue;
wordBreakRe(s, dict, path + word, i + 1, res);
}
}
}相关文章
- All Permutations II2016-01-10
- All Permutation2016-01-10
- All Subsets2016-01-10
- Best Time to Buy and Sell Stock II2016-01-10
已恢复到上次阅读位置