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 }

 

  

转载于:https://www.cnblogs.com/felixpan/p/4783860.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值