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 ArrayList<String> wordBreak(String s, Set<String> dict) {
ArrayList<String> res = new ArrayList<String>();
if (s == null || s.length() == 0 || dict.isEmpty() || dict.size() == 0) {
return res;
}
int maxLength = 0;
for (String word : dict) {
maxLength = Math.max(maxLength, word.length());
}
helperBreak(s, dict, res, "", maxLength, 0);
return res;
}
private void helperBreak(String s, Set<String> dict, ArrayList<String> res, String item, int maxLength, int pos) {
if (pos == s.length()) {
res.add(item);
return;
}
for (int i = 1; i <= maxLength && i + pos <= s.length(); i++) {
String word = s.substring(pos, pos + i);
if (dict.contains(word)) {
helperBreak(s, dict, res, item.length() >= 1 ? item + " " + word : word, maxLength, pos + i);
}
}
}
}
Or use dynamic programming. Store the possible sentences ending at each position in an array list, after iteration, return the last element in that array list. This way can save time, but requires much more space.
public ArrayList<String> wordBreak(String s, Set<String> dict) {
if (s == null || s.length() == 0 || dict.isEmpty() || dict.size() == 0 || !canWordBreak(s, dict)) {
return new ArrayList<String>();
}
boolean[] canBreak = new boolean[s.length() + 1];
canBreak[0] = true;
ArrayList<ArrayList<String>> sentence = new ArrayList<ArrayList<String>>();
for (int i = 0; i <= s.length(); i++) {
sentence.add(new ArrayList<String>());
}
sentence.get(0).add("");
int maxLength = 0;
for (String word : dict) {
maxLength = Math.max(maxLength, word.length());
}
for (int i = 1; i <= s.length(); i++) {
for (int j = 1; j <= maxLength && j <= i; j++) {
String word = s.substring(i - j, i);
if (canBreak[i - j] && dict.contains(word)) {
canBreak[i] = true;
for (String ss : sentence.get(i - j)) {
sentence.get(i).add(ss + (ss == "" ? "" : " ") + word);
}
}
}
}
return sentence.get(s.length());
}
}