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

[Leetcode] Word BreakII

时间:2014-06-16 06:22:37      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   http   

Question:

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

----------------------------------------------

Solution:

dfs.

但是需要注意的是,在dfs之前,需要判断这个string能不能被这个dictionary分割(Word Break)。

bubuko.com,布布扣
 1 public class Solution {
 2     public List<String> wordBreak(String s, Set<String> dict) {
 3         List<String> result=new ArrayList<String>();
 4         if(!wordBreakPossible(s,dict)) return result;
 5         dfs(s,dict,result,"",0);
 6         return result;
 7     }
 8 
 9     private void dfs(String s, Set<String> dict, List<String> result,String temp, int start) {
10         // TODO Auto-generated method stub
11         if(start==s.length())
12             result.add(temp);
13         else{
14             if(start!=0)
15                 temp+=" ";
16             for(int i=start;i<s.length();i++){
17                 String word=s.substring(start, i+1);
18                 if(dict.contains(word))
19                     dfs(s,dict,result,temp+word,i+1);
20             }            
21         }
22     }
23 
24     private boolean wordBreakPossible(String s, Set<String> dict) {
25         // TODO Auto-generated method stub
26         boolean[] state=new boolean[s.length()+1];
27         state[0]=true;
28         for(int i=1;i<=s.length();i++){
29             for(int j=i-1;j>=0;j--){
30                 if(state[j]&&dict.contains(s.substring(j, i))){
31                     state[i]=true;
32                     break;
33                 }
34                 
35             }
36         }
37         return state[s.length()];
38     }
39 }
bubuko.com,布布扣

 

[Leetcode] Word BreakII,布布扣,bubuko.com

[Leetcode] Word BreakII

标签:style   class   blog   code   java   http   

原文地址:http://www.cnblogs.com/Phoebe815/p/3784035.html

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