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];
        }
    };
  • 相关阅读:
    Making a CocoaPod
    关于Http
    The podfile
    iOS 8个实用小技巧(总有你不知道的和你会用到的)
    关于深拷贝浅拷贝
    适配ios10(iTunes找不到构建版本)
    iOS 10 推送的简单使用
    __block 和 __weak的区别
    Masonry使用注意事项
    iOS数字键盘自定义按键
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4918289.html
Copyright © 2011-2022 走看看