题目链接:http://oj.leetcode.com/problems/word-break/
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"
.
算是一道比较简单的DP题吧,dp[i]表示前i项可不可以拆开,dp[i]=dp[k]&dict.count(s.substr(i,i-k+1))
code:
// dp[j]=dp[k]&dict.count(s.substr(k,j));
//dp[i]表示前i项可不可以
class Solution
{
public:
bool wordBreak(string s, unordered_set<string> &dict)
{
if(s.size()==0)
return true;
vector<bool> dp(s.size()+1,false);
dp[0]=true;//啥都没有自然为true;
for(int i=1;i<=s.size();i++)
{
if(dp[i-1])
{
for(int j=i-1;j<s.size();j++)
{
string tmp=s.substr(i-1,j-(i-1)+1);
if(dict.count(tmp)>0)
{
dp[j+1]=true;
}
}
}
}
return dp[s.size()];
}
};