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