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 }