Question:
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".
分析:一开始先用的递归算法,但是系统报错:
Submission Result: Time Limit Exceeded
Last executed input:
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]
递归代码如下:
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
int len = s.size();
int start = 0;
bool contain = false;
if (s.size() < 1) return true;
for (int j = 1; j <= len; j++)
{
string str = s.substr(start, j - start);
if (dict.count(str) == 1)
{
if (str.size() == s.size()) return true;
else contain = wordBreak(s.substr(j), dict);
}
if (contain) return true;
}
return false;
}
};
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
if(s.empty()||dict.empty()) return false;
vector<bool> f(s.size() + 1, false);
f[0] = true;
for (int i = 1; i <= s.size(); i++)
{
for (int j = 0; j < i; j++)
{
if (f[j] && dict.count(s.substr(j, i-j)))
{
f[i] = true;
break;
}
}
}
return f[s.size()];
}
};

本文探讨了如何解决给定字符串能否被拆分为一个或多个字典中词汇的问题。通过对比递归方法与动态规划方法,展示了动态规划如何显著提高算法效率。
1607

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



