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"
.
判断字符串能否由给定字典组成。
DFS写会T,dp就过了。
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
vector<bool> dp(s.size()+1, false);
dp[0] = true;
for (int i = 1; i<= s.size(); i++)
{
for(int j = 0; j < i; j++)
{
if(!dp[j]) continue;
if(wordDict.find(s.substr(j, i-j)) != wordDict.end())
{
dp[i] = true;
break;
}
}
}
return dp[s.size()];
}
};