本题题目要求如下:
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]为true,且s.subtr(i, len-i)可以在dict中查找到,则dp[len]为true,
代码如下:
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int sz = s.length();
vector<bool> dp(sz + 1, false);
dp[0] = true;
for (int len = 1; len <= sz; ++len) {
for (int i = 0; i < len; ++i) {
if (dp[i] == true and wordDict.find(s.substr(i, len - i)) != wordDict.end()) {
dp[len] = true;
}
}
}
return dp[sz];
}
};