public class Solution {
HashMap<Integer, List<String>> map = new HashMap<Integer, List<String>>();
public List<String> wordBreak(String s, List<String> wordDict) {
Set<String> wordSet = new HashSet<String>();
for (String word : wordDict) {
wordSet.add(word);
}
int maxLength = findMaxLength(wordSet);
return helper(s, wordSet, 0, maxLength);
}
private List<String> helper(String s, Set<String> wordSet, int index, int maxLength) {
List<String> wordList = new ArrayList<String>();
if (index == s.length()) {
wordList.add("");
return wordList;
}
for (int i = index + 1; i <= index + maxLength && i <= s.length(); i++) {
String tmp = s.substring(index, i);
if (wordSet.contains(tmp)) {
List<String> tmpList;
if (map.containsKey(i)) {
tmpList = map.get(i);
} else {
tmpList = helper(s, wordSet, i, maxLength);
}
for (String word : tmpList) {
wordList.add(tmp + (word.equals("") ? "" : " ") + word);
}
}
}
map.put(index, wordList);
return wordList;
}
private int findMaxLength(Set<String> wordSet) {
int maxLength = 0;
for (String word : wordSet) {
maxLength = Math.max(maxLength, word.length());
}
return maxLength;
}
}