publicclassSolution{ public List<String> wordBreak(String s, Set<String> dict){ List<String> result = new LinkedList<String>(); if (s.length() == 0) return result; generate(s, dict, new HashSet<String>(), result, new StringBuilder()); return result; }
privatebooleangenerate(String s, Set<String> dict, Set<String> mismatch, List<String> result, StringBuilder sentence){ if (s.length() == 0) { result.add(sentence.toString()); returntrue; } boolean canBreak = false; for (String word : dict) { if (s.startsWith(word)) { String suffix = s.substring(word.length(), s.length()); if (!mismatch.contains(suffix)) { StringBuilder newSentence = new StringBuilder(sentence); if (newSentence.length() != 0) newSentence.append(" "); newSentence.append(word); if (generate(suffix, dict, mismatch, result, newSentence)) { canBreak = true; } else { mismatch.add(suffix); } } } } return canBreak; } }