Word Break II

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].

A solution is ["cats and dog", "cat sand dog"].

 1 public class Solution {
 2     public ArrayList<String> wordBreak(String s, Set<String> dict) {
 3         ArrayList<String>  res = new ArrayList<String> ();
 4         if(s.length()<=0) return res;
 5         StringBuilder sb = new StringBuilder();
 6         DFS(s,dict,new boolean[s.length()+1],0,sb,res);
 7         return res;
 8     }
 9     public void DFS(String s,Set<String> dict,boolean[]p,int start, StringBuilder output,ArrayList<String>res){
10         if(s.length()==start){
11             String temp = output.toString();
12             temp = temp.substring(0,temp.length()-1);
13             res.add(temp);
14             return;
15         }
16         for(int i=start;i<s.length();i++){
17             String piece = s.substring(start,i+1);
18             if(dict.contains(piece) && !p[i+1]){
19                 output.append(piece);
20                 output.append(" ");
21                 int curSize = res.size();
22                 DFS(s,dict,p,i+1,output,res);
23                 if(res.size()==curSize)
24                     p[i+1] = true;
25                 int end = output.length();
26                 int begin = end - piece.length()-1;
27                 output.delete(begin,end);
28             }
29         }
30     }
31 }
View Code

 res.add(sb.toString().substring(0,sb.length()-1));

int begin = end -pieces.length()-1;

posted @ 2014-02-22 13:07  krunning  阅读(262)  评论(0编辑  收藏  举报