问题描述:
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.
示例, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
这是一道可用动态规划求解的问题,对于数组s若能分割为dict中的若干个单词,那么肯定存在s的字串s1和s2满足s在dict中所满足的条件。
过程详见代码:
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> dict(wordDict.begin(), wordDict.end());
int n = s.length();
vector<bool> dp(n, 0);
dp[0] = (dict.find(s.substr(0, 1)) != dict.end());
for (int i = 1; i < n; i++)
{
dp[i] = (dict.find(s.substr(0, i + 1)) != dict.end());
for (int j = i - 1; j >= 0; j--)
{
if (dp[i]) break;
if (!dp[j]) continue;
dp[i] = (dict.find(s.substr(j + 1, i - j)) != dict.end());
}
}
return dp[n-1];
}
};