Leetcode: Word Break

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.