-
题目:
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".
-
idea
- 使用动态规划的思想。dp[i] = any(dp[j], s.substr(j, i-j)存在于字典)
- 即dp的第i个元素意义为s[0:i+1]为一个句子,假如前j个字符是个句子即dp[j]以及s[j:i]是一个单词,则dp[i]=true
- 初始化dp[0]=true。因此当前i个字符是一个单词的时候,dp[i]应该为true,即dp[0]应该赋值为true
- 结果为dp[len]
- dp[i]的意义为前i个字符是否能组成一个句子,即i是当前总长度。j是前半段的长度
-
code
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
int len = s.size();
vector<bool> dp(len+1, false);
dp[0] = true;
for (int i = 1; i < len+1; i++){
for (int j = 0; j < i; j++){
if (dp[j] && dict.find(s.substr(j, i-j)) != dict.end()){
dp[i] = true;
break;
}
}
}
return dp[len];
}
};