|
| 1 | +public class Solution { |
| 2 | + public List<String> wordBreak(String s, Set<String> dict) { |
| 3 | + List<String> results = new LinkedList<String>(); |
| 4 | + if (dict.size() == 0 || s.length() == 0) { return results; } |
| 5 | + int sl = s.length(); |
| 6 | + ArrayList<LinkedList<Integer>> dp = new ArrayList<LinkedList<Integer>>(sl); |
| 7 | + for (int i=0; i<sl; i++) { |
| 8 | + dp.add(null); |
| 9 | + } |
| 10 | + for (int i=sl-1; i>=0; i--) { |
| 11 | + for (int j=i+1; j<=sl; j++) { |
| 12 | + if (dict.contains(s.substring(i, j))) { |
| 13 | + if (j == sl || dp.get(j) != null) { |
| 14 | + if (dp.get(i) == null) { |
| 15 | + dp.set(i, new LinkedList<Integer>()); |
| 16 | + } |
| 17 | + dp.get(i).add(j); |
| 18 | + } |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + if (dp.get(0) == null) { |
| 23 | + return results; |
| 24 | + } |
| 25 | + |
| 26 | + generate(s, dp, 0, new StringBuilder(), results); |
| 27 | + return results; |
| 28 | + } |
| 29 | + |
| 30 | + public void generate(String s, ArrayList<LinkedList<Integer>> dp, int index, StringBuilder sb, List<String> results) { |
| 31 | + if (index == s.length()) { |
| 32 | + results.add(sb.toString()); |
| 33 | + return; |
| 34 | + } |
| 35 | + LinkedList<Integer> list = dp.get(index); |
| 36 | + for (int next: list) { |
| 37 | + StringBuilder newSb = new StringBuilder(sb); |
| 38 | + newSb.append(s.substring(index, next)); |
| 39 | + if (next != s.length()) { |
| 40 | + newSb.append(" "); |
| 41 | + } |
| 42 | + generate(s, dp, next, newSb, results); |
| 43 | + } |
| 44 | + } |
| 45 | +} |
0 commit comments