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

    本题如果暴力的话,超时

    本题用动规

    设dp[i]表示s[0,i)之间存在划分使分隔后的字符串都在dict里面

    dp[i]=

      true, 如果s[0,i)在dict里面

      true,如果dp[k]=true (即s[0,k)存在划分在dict里面)且s[k,i)在dict里面

      false,其他(默认)

      注意程序是前闭后开

    bool wordBreak(string s, unordered_set<string> &dict){
        int n = s.length();
        vector<bool> dp(n+1,false);
        dp[0]=true;
        for(int i = 1 ; i < n+1; ++ i){
            for(int j = 0 ; j < i; ++ j){
                if(dp[j]&&dict.find(s.substr(j,i-j))!=dict.end()){
                    dp[i] = true;
                    break;
                }    
            }
        }
        return dp[n];
    }

      

  • 相关阅读:
    用CSS开启硬件加速来提高网站性能
    vim中替换内容
    alias vi=vim
    PHP 多进程初识
    端口的查看
    PHP三种终止脚本执行:return,die,exit
    2021.3.14(每周总结)
    2021.3.13
    2021.3.12
    2021.3.11
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3795370.html
Copyright © 2011-2022 走看看