题目:
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".
class Solution {
public:
//DP
bool wordBreak(string s, unordered_set<string> &dict) {
if (s.size() == 0)
return false;
//f[i]表示s[0]...s[i]表示字符串能否用字典表示
vector<bool> f(s.size(), false);
for (int i = 0; i < s.size(); i++) {
if (isMatch(s.substr(0, i + 1), dict)) {
f[i] = true;
continue;
}
else {
for (int j = 0; j < i; j++) {
if (f[j]) {
f[i] = isMatch(s.substr(j + 1, i - j), dict);
if (f[i])
break;
}
}
}
}
return f[s.size() - 1];
}
private:
bool isMatch(string s, unordered_set<string> &dict) {
if (dict.find(s) != dict.end())
return true;
return false;
}
};
本文介绍了一种使用动态规划解决字符串是否能被字典中单词完全分割的问题。通过递归检查子串,实现高效判断。
1578

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



