class Solution {
/*
state:canBreak[i] means whether sb.substring(0, i) can be break
canBreak[i] = dict.contains(s.susbtring(j, i)) && canBreak[j]
i from [1, n]
j from [0, i)
initial:
canBreak[0] = true
res:
return canBreak[n]
*/
public boolean wordBreak(String s, List<String> wordDict) {
int n = s.length();
Set<String> dict = new HashSet<>();
for (String word : wordDict) {
dict.add(word);
}
boolean[] canBreak = new boolean[n + 1];
canBreak[0] = true;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
if (dict.contains(s.substring(j, i)) && canBreak[j]) {
canBreak[i] = true;
break;
}
}
}
return canBreak[n];
}
}
Word Break II
same idea of wordBreak, use memo to avoid duplicate calculation
use Map for memo, key is string, value is List<String> that can be break for key
optimization: get maxLen of word in wordDict, then we just need to iterate for length of maxLen instead of iterate through whole string s.
class Solution {
/*
same idea of wordBreak, use memo to avoid duplicate calculation
use Map for memo, key is string, value is List<String>
optimization: get maxLen of word in wordDict, then we just need to iterate for length of maxLen instead of iterate through whole string s.
*/
public List<String> wordBreak(String s, List<String> wordDict) {
Set<String> dict = new HashSet<>();
int maxLen = 0;
for (String word : wordDict) {
dict.add(word);
maxLen = Math.max(maxLen, word.length());
}
return helper(s, dict, new HashMap<String, List<String>>(), maxLen);
}
//return all result for string s
private List<String> helper(String s, Set<String> dict, Map<String, List<String>> memo,int maxLen) {
if (memo.containsKey(s)) {
return memo.get(s);
}
List<String> res = new ArrayList<>();
if (s.length() == 0) return res;
for (int i = 1; i <= maxLen && i <= s.length(); i++) {
String word = s.substring(0, i);
if (!dict.contains(word)) continue;
if (i == s.length()) {
res.add(word);
break;
} else {
String suffix = s.substring(i);
List<String> segmentations = helper(suffix, dict, memo, maxLen);
for (String segmentation : segmentations) {
res.add(word + " " + segmentation);
}
}
}
memo.put(s, res);
return res;
}
}