题目
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.
Example
For example, given
s = “leetcode”,
dict = [“leet”, “code”].
Return true because “leetcode” can be segmented as “leet code”.
解法
dp[i]表示s[1..i]是否可以被分词
dp[0] = true;
for i:1->n
for j:i-1->0
若dp[i]=true且s的子串substr(j, i-j)在字典中,则dp[i]=true
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
vector<bool> dp(s.length()+1, false);
dp[0] = true;
for (int i=1; i<=s.length(); i++){
for (int j=i-1; j>=0; j--){
if (dp[j] && find(wordDict.begin(),wordDict.end(),s.substr(j, i-j)) != wordDict.end()){
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
};