zoukankan      html  css  js  c++  java
  • 139. Word Break (String; DP)

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

    法I: DP, 二位数组。用所求值“——是否可以被分段,作为状态。

    class Solution {
    public:
        bool wordBreak(string s, unordered_set<string>& wordDict) {
            //dp[i][j]: s[i...j] can be egemented in dict
            //dp[i][j] = dp[i][k] && d[k][j]
            int len = s.length();
            vector<vector<bool>> dp(len,vector<bool>(len,false)); 
            for(int i = 0; i < len; i++){
                if(wordDict.find(s.substr(0,i+1))!=wordDict.end()) dp[0][i]=true;
                for(int j = 1; j <= i; j++){
                    if((wordDict.find(s.substr(j,i-j+1))!=wordDict.end()) && dp[0][j-1]) dp[0][i]=true;
                }
            }
            return dp[0][len-1];
        }
    };

    法II:发现只用到了dp[0][i], i = 0...len-1=>使用一维数组。

    class Solution {
    public:
        bool wordBreak(string s, unordered_set<string>& wordDict) {
            //dp[i]: s[0...i] can be egemented in dict
            //dp[i] = dp[0][k] && d[k][i]
            int len = s.length();
            vector<bool> dp(len,false);
            for(int i = 0; i < len; i++){
                if(wordDict.find(s.substr(0,i+1))!=wordDict.end()) dp[i]=true;
                for(int j = 1; j <= i; j++){
                    if((wordDict.find(s.substr(j,i-j+1))!=wordDict.end()) && dp[j-1]) dp[i]=true;
                }
            }
            return dp[len-1];
        }
    };
  • 相关阅读:
    脚本添加crontab任务
    docker mysql8 注意
    使用 logrotate 清理日志
    腾讯云cos对象在线显示
    快速部署私人git服务--基于docker化Gogs
    grep 使用
    vsftpd 新增虚拟用户
    unistd.h
    ffmpeg
    H264视频压缩算法
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4918289.html
Copyright © 2011-2022 走看看