Word Break II leetcode java


題目

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

 

題解

這道題不僅僅是看是不是wordbreak,還需要在此基礎上把所有word break的結果保存。

為了把所有可能性都保存,那么就使用DFS方法來解決。DFS主要就是跳的層次不容易看出,我下面就以字符串leetcode字典le l et eet code作為例子畫了一張圖,大概講解了如何遞回和返回,這樣更加有助於理解。


 

代碼如下:

 

 1      public  boolean wordBreakcheck(String s, Set<String> dict) {
 2          if(s== null || s.length()==0)
 3              return  true;
 4          boolean[] res =  new  boolean[s.length()+1];
 5         res[0] =  true;
 6          for( int i=0;i<s.length();i++){
 7             StringBuilder str =  new StringBuilder(s.substring(0,i+1));
 8              for( int j=0;j<=i;j++){
 9                  if(res[j] && dict.contains(str.toString())){
10                     res[i+1] =  true;
11                      break;
12                 }
13                 str.deleteCharAt(0);
14             }
15         }
16          return res[s.length()];
17     }
18     
19      public ArrayList<String> wordBreak(String s, Set<String> dict) {  
20         ArrayList<String> res =  new ArrayList<String>();  
21          if(s== null || s.length()==0)  
22              return res;
23          if(wordBreakcheck(s,dict))
24             helper(s,dict,0,"",res);  
25          return res;  
26     }  
27      private  void helper(String s, Set<String> dict,  int start, String item, ArrayList<String> res){  
28          if(start>=s.length()){  
29             res.add(item);  
30              return;  
31         }
32         
33         StringBuilder str =  new StringBuilder();  
34          for( int i=start;i<s.length();i++){  
35             str.append(s.charAt(i));  
36              if(dict.contains(str.toString())){  
37                 String newItem =  new String();  
38                  if(item.length()>0)
39                     newItem = item + " " + str.toString();
40                  else
41                     newItem = str.toString();
42                 helper(s,dict,i+1,newItem,res);  
43             }  
44         }  
45     }  

 Reference: http://blog.csdn.net/linhuanmars/article/details/22452163


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM