LeetCode -- Word Break 動態規划,詳細理解


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

     

【思路】

對於該問題我一開始的做法就是,盡可能匹配,例如 s = "abcdefabc" dict=["abc","def"] 我只要把s 中所有存在於字典中的詞語去掉,最后如果s沒有任何字母則表示能夠break;

但是問題來了,s="aaaaaaa" dict=["aaa","aaaa"],這個時候就會直接用aaa去把s分成 aaa,aaa,a;從而返回false.

再比如,s="abcdeefg" dict=["ab","cde","ee","cd","fg"],當用字典中的"cde"去分割的時候,結果是 ab, cde, e, fg; 從而返回false.

     

【動態規划解題】

【重點 ★★】

從s[2]=c開始,我們發現了兩個字典詞語與之相匹配,即:cde,cd,我們標記出他們能拼接的長度

ab cdeefg

ab

     cde

     cd

--->接下來,我們就從 efg或者eefg的位置開始匹配

   

【代碼】

 1 public class Solution {
 2     public boolean wordBreak(String s, Set<String> dict){
 3         boolean[] t =new boolean[s.length()+1];
 4         t[0]=true;//set first to be true, why?
 5         //Because we need initial state
 6  
 7         for(int i=0; i<s.length(); i++){
 8             //should continue from match position
 9             if(!t[i])
10                 continue;
11  
12             for(String a: dict){
13                 int len = a.length();
14                 int end = i + len;
15                 if(end > s.length())
16                     continue;
17  
18                 if(t[end])continue;
19  
20                 if(s.substring(i, end).equals(a)){
21                     t[end]=true;
22                 }
23             }
24         }
25  
26         return t[s.length()];
27     }
28 }

 

  


免責聲明!

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



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