LeetCode -- Word Break 动态规划,详细理解

时间:2023-03-09 12:56:41
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.

【动态规划解题】

LeetCode -- Word Break  动态规划,详细理解

【重点 ★★】

从s[2]=c开始,我们发现了两个字典词语与之相匹配,即:cde,cd,我们标记出他们能拼接的长度

ab cdeefg

ab

     cde

     cd

--->接下来,我们就从 efg或者eefg的位置开始匹配

LeetCode -- Word Break  动态规划,详细理解

【代码】

 public class Solution {
public boolean wordBreak(String s, Set<String> dict){
boolean[] t =new boolean[s.length()+1];
t[0]=true;//set first to be true, why?
//Because we need initial state for(int i=0; i<s.length(); i++){
//should continue from match position
if(!t[i])
continue; for(String a: dict){
int len = a.length();
int end = i + len;
if(end > s.length())
continue; if(t[end])continue; if(s.substring(i, end).equals(a)){
t[end]=true;
}
}
} return t[s.length()];
}
}