Word Break leetcode java


題目:

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

 

題解

這道題的題解轉載自Code ganker,他寫的很好。地址:http://blog.csdn.net/linhuanmars/article/details/22358863

原題鏈接: http://oj.leetcode.com/problems/word-break/ 
這道題仍然是動態規划的題目,我們總結一下動態規划題目的基本思路。首先我們要決定要存儲什么歷史信息以及用什么數據結構來存儲信息。然后是最重要的遞推式,就是如從存儲的歷史信息中得到當前步的結果。最后我們需要考慮的就是起始條件的值。

接 下來我們套用上面的思路來解這道題。首先我們要存儲的歷史信息res[i]是表示到字符串s的第i個元素為止能不能用字典中的詞來表示,我們需要一個長度 為n的布爾數組來存儲信息。然后假設我們現在擁有res[0,...,i-1]的結果,我們來獲得res[i]的表達式。思路是對於每個以i為結尾的子 串,看看他是不是在字典里面以及他之前的元素對應的res[j]是不是true,如果都成立,那么res[i]為true,寫成式子是

假 設總共有n個字符串,並且字典是用HashSet來維護,那么總共需要n次迭代,每次迭代需要一個取子串的O(i)操作,然后檢測i個子串,而檢測是 constant操作。所以總的時間復雜度是O(n^2)(i的累加仍然是n^2量級),而空間復雜度則是字符串的數量,即O(n)。代碼如下:


 

 1  public  boolean wordBreak(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     {
 8         StringBuilder str =  new StringBuilder(s.substring(0,i+1));
 9          for( int j=0;j<=i;j++)
10         {
11              if(res[j] && dict.contains(str.toString()))
12             {
13                 res[i+1] =  true;
14                  break;
15             }
16             str.deleteCharAt(0);
17         }
18     }
19      return res[s.length()];
20 }


免責聲明!

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



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