码迷,mamicode.com
首页 > 其他好文 > 详细

Word Break II

时间:2014-08-18 20:36:22      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:算法   dfs   dp   

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"].

dfs超时

public class Solution {
    public List<String> wordBreak(String s, Set<String> dict) {
       LinkedList<String> res=new LinkedList<String>();
       LinkedList<String> path=new LinkedList<String>();
       if(s==null || dict==null || dict.size()==0) return res;
       
       int n=s.length();
       boolean []f=new boolean[n+1];
       boolean [][]prev=new boolean[n+1][n];
       f[0]=true;
       //dp
       for(int i=1;i<=n;i++){
           for(int j=i-1;j>=0;j--){
               if( f[j] && dict.contains( s.substring(j,i) ) ){
                   f[i]=true;
                   prev[i][j]=true;
               }
           }
       }

       getPath(s.length(),s,prev,res,path);
       return res;
    }
    //dfs
    public void getPath(int curr,String s, boolean [][]prev,LinkedList<String> res,LinkedList<String> path){
        if(curr==0){
            StringBuilder sb=new StringBuilder();
            for(String ss : path){
                sb.append(ss);
                sb.append(" ");
            }
            res.add(sb.toString().trim());
        }
        for(int i=0;i<curr;i++){
            if(prev[curr][i]){
                path.addFirst(s.substring(i,curr));
                getPath(i,s,prev,res,path);
                path.pollFirst();
            }
        }
    }
}




Word Break II,布布扣,bubuko.com

Word Break II

标签:算法   dfs   dp   

原文地址:http://blog.csdn.net/dutsoft/article/details/38663357

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!