zoukankan      html  css  js  c++  java
  • 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 }

      

  • 相关阅读:
    揭秘淘宝286亿海量图片存储与处理架构
    从能做的事做起,做越来越多的事
    用表驱动代替switchcase
    文件过滤驱动中的重入处理
    谈谈对APC的一点理解
    StartIo例程的作用
    C++各大名库的介绍
    IRQL
    FastIO
    一道面试题,看这段代码最后抛出什么异常
  • 原文地址:https://www.cnblogs.com/felixpan/p/4783860.html
Copyright © 2011-2022 走看看