
class Solution {
public:
//dp[i]表示字符串s的前i个字符是否能够匹配上
//dp[i]为true由dp[j](j < i)为true和s[j:i](s下标从0开始)存在在wordDict中转移
bool dp[1005];
bool wordBreak(string s, vector<string>& wordDict) {
set<string> word;
int sz = s.size();
for(int i = 0; i < wordDict.size(); i++){
word.insert(wordDict[i]);
}
dp[0] = true;
for(int i = 1; i <= sz; i++){
for(int j = 0; j < i; j++){
string tmp = s.substr(j, i - j);
if(dp[j] && word.find(tmp) != word.end()){
dp[i] = true;
break;
}
}
}
return dp[sz];
}
};
该代码示例展示了一个使用动态规划解决字符串是否能根据给定字典拆分成合法词组的问题。通过遍历字典并构建动态规划数组,判断每个子串是否在字典中,最终确定整个字符串是否可拆分。
1575

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



