This is the extension of word break problem.
Add traceback for the solution.
public List<String> wordBreak(String s, Set<String> dict) {
int len = s.length();
boolean[] dp = new boolean[len+1];
List<List<Integer>> prevs = new ArrayList<List<Integer>>();
for (int i=0; i<=len; i++) {
prevs.add(new ArrayList<Integer>());
}
dp[0] = true;
for (int i=1; i<=len; i++) {
for (int j=0; j<i; j++) {
if (dp[j] && dict.contains(s.substring(j, i))) {
prevs.get(i).add(j);
dp[i]=true;
}
}
}
List<String> res = new ArrayList<String>();
buildRes(s, prevs, len, res, "");
return res;
}
private void buildRes(String s, List<List<Integer>> prevs, int end, List<String> res, String curr) {
List<Integer> prev = prevs.get(end);
for (int i=0; i<prev.size(); i++) {
int newEnd = prev.get(i);
String sub = s.substring(newEnd, end);
String r = sub;
if (!curr.equals("")) {
r = r + " " + curr;
}
if (newEnd == 0) {
res.add(r);
} else {
buildRes(s, prevs, newEnd, res, r);
}
}
}
No comments:
Post a Comment