Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet
code"
.
UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
这题目一看就是动态规划大法,该动态规划方程与一般的有点小区别,动态规划方程如下:
初始化:dp[s.size()+1], dp[0] = true
j = 0,1,2,...,i-1,if(dp[j] && s.substr(j,i-j) in wordDict) dp[i] = true;
代码如下:
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
bool* dp = new bool[s.size()+1];
memset(dp,false,sizeof(bool)*(s.size()+1));
dp[0] = true;
for(int i=1;i<=s.size();i++)
for(int j=i-1;j>=0;j--)
{
string tmp = s.substr(j,i-j);
if(dp[j] && find(wordDict.begin(),wordDict.end(),tmp) != wordDict.end())
{
dp[i] = true;
break;
}
}
return dp[s.size()];
}
};