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> wordDict) {
ArrayList<String> res = new ArrayList<>();
if (s == null || s.length() == 0) {
return res;
}
if (wordBreakcheck(s, wordDict)) {
solve(s, wordDict, 0, "", res);
}
return res;
}
private void solve(String s, Set<String> wordDict, int start, String item,
ArrayList<String> res) {
if (start >= s.length()) {
res.add(item);
return;
}
StringBuffer stringBuffer = new StringBuffer();
for (int i = start; i < s.length(); i++) {
stringBuffer.append(s.charAt(i));
if (wordDict.contains(stringBuffer.toString())) {
String tmp = new String();
if (item.length() > 0) {
tmp = item + " " + stringBuffer.toString();
} else {
tmp = stringBuffer.toString();
}
solve(s, wordDict, i+1, tmp, res);
}
}
}
private boolean wordBreakcheck(String s, Set<String> wordDict) {
if (s == null || s.length() == 0) {
return true;
}
boolean[] dp = new boolean[s.length()+1];
dp[0] = true;
for (int i = 0; i < s.length(); i++) {
StringBuffer stringBuffer = new StringBuffer(s.substring(0, i+1));
for (int j = 0; j <= i; j++) {
if (dp[j] && wordDict.contains(stringBuffer.toString())) {
dp[i+1] = true;
break;
}
stringBuffer.deleteCharAt(0);
}
}
return dp[s.length()];
}
}
5185

被折叠的 条评论
为什么被折叠?



