[leedcode 140] 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"].

public class Solution {
    //本题借用前一个题目,在进行拆分字符串之前,先调用isCanBreak函数,确定是否能够拆分。如果可以拆分,这里有是从wordDict入手的,
    //取出dict的每一个单词,如果是s的子串,则保存起来,并且继续DFS s子串,当s全部拆分完,保存中间结果
    List<String> res;
    List<String> seq;
    public List<String> wordBreak(String s, Set<String> wordDict) {
        res=new ArrayList<String>();
        seq=new ArrayList<String>();
        getRes(s,wordDict);
        return res;
    }
    public void getRes(String s,Set<String> wordDict){
        
        if(s.length()==0){
            StringBuilder temp=new StringBuilder();
            for(String t:seq){
                temp.append(" "+t);
            }
            res.add(temp.toString().trim());////
            return;
        }
        if(!isCanBreak(s,wordDict))
                return;///////
        
        for(String dict:wordDict){
            if(dict.length()>s.length()) continue;
            String temp=s.substring(0,dict.length());
            if(temp.equals(dict)){
                seq.add(temp);
                getRes(s.substring(dict.length()),wordDict);
                seq.remove(seq.size()-1);
            }
        }
        
    }
    public boolean isCanBreak(String s,Set<String> wordDict){
        int len=s.length();
        boolean dp[]=new boolean[len+1];
        dp[0]=true;
        for(int i=1;i<=len;i++){
            for(int j=0;j<i;j++){
                if(dp[j]&&wordDict.contains(s.substring(j,i))){
                    dp[i]=true;
                    break;
                }
                   
            }
        }
        return dp[len];
    }
}

 

posted @ 2015-07-26 20:46  ~每天进步一点点~  阅读(204)  评论(0编辑  收藏  举报