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:
bool wordBreak(string s, unordered_set<string> &dict)
{
if (s.empty()) return false;
int length = s.length();
vector<bool> dp(length + 1, false);
dp[0]= true;
for (int len = 1; len <= length; len++)
{
for (int i = 0; i <= len; i++)
{
if (dp[i] && dict.find(s.substr(i, len - i)) != dict.end())
{
dp[len] = true;
break;
}
}
}
return dp[length];
}
};
我第一次做这题时,用迭代超时,用dp只找到N^3 解法就索性不做了,搁置一段时间后,当我用dp做完了 Interleaving String后再做这道题,就突然想通了,然后再在网上查找了别人的做法,发现好多人和我一样陷入了N^3时间复杂度的误区。
本文探讨了如何使用动态规划解决字符串分割问题,通过实例分析,详细解释了如何判断一个字符串能否被拆分成字典中包含的一个或多个单词。
2793

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



