确定代码的运行时间
Determine running time of the code
我今天写了以下dp代码,它工作得很好,因为它得到了一些提交点(这就是问题所在)。然而,我无法确定我的代码的运行时间。我觉得这是O(n^2 * log D)
,但我无法证明。
class Solution {
public:
unordered_map<string, bool> m;
bool wordBreak(string s, unordered_set<string>& wordDict) {
int n = s.length();
string t = "";
for(int i=0;i<n;i++){
t += s.at(i);
//cout << t << endl;
if(wordDict.find(t) != wordDict.end()){
m[t] = true;
string x = "";
for(int j=i+1;j<n;j++){
x += s.at(j);
}
if(x == ""){
return true;
}
if(m.find(x) != m.end()){
if(m[x] == true){
return true;
}else{
continue;
}
}else{
if(wordBreak(x, wordDict)){
m[x] = true;
return true;
}else{
//cout << x << endl;
m[x] = false;
continue;
}
}
}else{
//m[t] = false;
}
}
return false;
}
};
它似乎具有O(n*n)
复杂性。你使用记忆和你的算法的每一步产生至少一个新的值在m
。在任何字符串中都有n*n/2
子字符串,因此在最坏的情况下,您将找到具有n*n/2段的整个字符串的解决方案。
PS:考虑unordered_map与O(1)
兼容
在您的情况下,认为unordered_map适用于O(n)可能更合适。m.find
将需要为它的参数计算哈希值,这是字符串。如果您存储索引而不是字符串本身,可能会工作得更快。
首先我将重写如下(未经测试):
class Solution {
public:
unordered_map<string, bool> m;
bool wordBreak(string s, unordered_set<string>& wordDict)
{
while (!s.empty())
{
int n = s.size() ;
for(int i=0;i<n;i++){
//cout << t << endl;
if(wordDict.find(s.substr(0, i)) != wordDict.end()){
m[t] = true;
s = s.substr(i) ;
break ;
}
return !m.empty();
}
};
基本思想是,一旦你找到一个匹配,然后你可以从字符串中删除匹配的部分。那么我就说它是n * logD。毕竟,您只在for循环上执行了一次。假设你在m <N,那么你得到一个新的循环(N>
我是这样解决的。
bool wordBreak(string s, unordered_set<string>& wordDict) {
if (s.empty()) return true;
vector<bool> dp(s.size(), false);
for (int i = 0; i < dp.size(); ++i)
{
for (int j = i; j >= 0; --j)
{
if (wordDict.find(s.substr(j, i - j + 1)) != wordDict.end() &&
(j == 0 || dp[j - 1]))
{
dp[i] = true;
break;
}
}
}
return dp.back();
}
相关文章:
- KMP算法和LPS表构造的运行时间
- 如何减少代码的运行时间以对齐文本?
- 此代码中运行时间错误的原因是什么
- 一行代码的Arduino运行时间
- 该递归代码用于计算指数的运行时间是多少
- (如何)我可以使用LLVM机器代码分析器预测代码片段的运行时间
- 我的代码在大O时间中的运行时间
- 如何在Visual Studio中设置C /C代码仅在一个线程中运行以测试运行时间
- 为什么这两个代码之间的运行时间差异这么长
- 更改Linux用户从C/C 代码运行时间
- 为什么相同的代码运行时间不同
- 运行时间比较 - 类似的代码运行速度慢 4 倍
- 以下 Prim 算法代码的运行时间
- 调试代码的运行时间比发布代码长几个数量级
- 在展开的链表上运行大约需要40%的代码运行时间——有什么明显的方法可以优化它吗
- 如何测量C代码的运行时间比较
- 确定代码的运行时间
- 测量c++和CUDA代码的运行时间
- 如何在不到1秒的时间内运行此代码
- 如何进一步减少此代码的运行时间