標籤:style blog http color io os ar for 資料
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, givens = "leetcode",dict = ["leet", "code"].Return true because "leetcode" can be segmented as "leet code".
難度95,DP的經典題,參考了一下網上思路:
首先我們要決定要儲存什麼曆史資訊以及用什麼資料結構來儲存資訊。然後是最重要的遞推式,就是如從儲存的曆史資訊中得到當前步的結果。最後我們需要考慮的就是起始條件的值。
接下來我們套用上面的思路來解這道題。首先我們要儲存的曆史資訊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 class Solution { 2 public boolean wordBreak(String s, Set<String> dict) { 3 if (s == null || s.length() == 0) { 4 return true; 5 } 6 if (s != null && s.length() != 0 && dict.isEmpty()) { 7 return false; 8 } 9 boolean[] res = new boolean[s.length()+1];10 res[0] = true;11 for (int i=0; i<s.length(); i++) {12 StringBuffer str = new StringBuffer(s.substring(0, i+1));13 for (int j=0; j<=i; j++) {14 if (res[j] && dict.contains(str.toString())) {15 res[i+1] = true;16 break;17 }18 str.deleteCharAt(0);19 }20 }21 22 return res[s.length()];23 }24 }
Leetcode: Word Break