首页 > 其他 > 详细

Word Break II

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!