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

LeetCode140:Word Break||

时间:2015-06-08 00:47:03      阅读:159      评论: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"].

思路:和LeetCode93:Restore IP Adress一样,DFS

技术分享
public class Solution {
   public List<String> wordBreak(String s, Set<String> wordDict) {
        List<String> ans=new ArrayList<String>();
        if(s==null||wordDict.isEmpty()||!canBreak(s, wordDict))
            return ans;
        dfs(ans,wordDict,s,0,"");
        return ans;
    }
    
    private void dfs(List<String> ans,Set<String> wordDict,String s, int start, String string) {
        // TODO Auto-generated method stub
        if(start>=s.length()){
            ans.add(string); 
                     return ;
                  }
                  
        /*     if(end==true){
                    String sub=s.substring(start);
                   if(wordDict.contains(sub))
                         ans.add(string+" "+sub);
                         return;
                     }*/
                     
        
    for(int i=1;start+i<=s.length();i++){
        /*if((start+i)==s.length())
            end=true;*/
        String sub=s.substring(start,start+i);
        if(wordDict.contains(sub)){
           
           
            if(start==0){
                dfs(ans,wordDict, s, start+i,sub);
          }else{
                dfs(ans, wordDict,s, start+i, string+" "+sub);
           }
        }
        }
    }
    

    public boolean canBreak(String s, Set<String> wordDict) {
        int m=s.length();
        boolean isSegmented[]=new boolean[m+1];
        isSegmented[0]=true;
        int start=0;
        for(int i=0;i<m;i++)
        for(int j=0;j<=i;j++){
        isSegmented[i+1]=isSegmented[j]&&wordDict.contains(s.substring(j,i+1));
        if(isSegmented[i+1])
        break;
        }
        return isSegmented[m];
        }
}
View Code

 

LeetCode140:Word Break||

标签:

原文地址:http://www.cnblogs.com/gonewithgt/p/4559667.html

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