139. Word Break (String; DP)

╄→尐↘猪︶ㄣ 提交于 2020-01-28 07:49:47

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];
    }
};

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!