简单动态规划,dp[i]表示字符串s[0~i]是否可分的bool值。
画表格可以理解:
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
int len=s.length();
vector<bool> dp(len+1,false);
dp[0]=true;
for(int i=0;i<len;i++)
for(int j=i;dp[i]&&j<len;j++){
if(dict.find(s.substr(i,j-i+1))!=dict.end())
dp[j+1]=true;
}
return dp[len];
}
};
本文介绍了一种使用动态规划解决单词拆分问题的方法。通过一个布尔型动态规划数组dp来记录字符串s从开始到当前位置能否被字典中的单词完全覆盖。采用两层循环遍历字符串,利用哈希集合快速查找字典中是否存在对应的子串。
1199

被折叠的 条评论
为什么被折叠?



