问题描述
这是我的代码,我是在leetcode平台上编写的
const int N1 = 100+1;
const int N2 = 10e4+1;
class Solution {
public:
bool cache[N1][N2];
bool isSubsequence(string s,string t) {
int n1 = s.size();
int n2 = t.size();
for(int i=0; i<=n1; i++) {
for(int j=0; j<=n2; j++) {
if(i == 0)
cache[i][j] = true;
if(j == 0)
cache[i][j] = false;
if(s[i-1] == t[j-1])
cache[i][j] = cache[i-1][j-1];
else
cache[i][j] = cache[i][j-1];
}
}
return cache[n1][n2];
}
};
它给出以下错误,我不知道为什么。请帮忙。 error image
解决方法
我解决了这个问题。错误是由于数组索引超出范围。 这是编辑部分:
if(i == 0)
cache[i][j] = true;
else if(j == 0)
cache[i][j] = false;
else if(s[i-1] == t[j-1])
cache[i][j] = cache[i-1][j-1];
else
cache[i][j] = cache[i][j-1];
};
,
我们无需为解决此问题而缓存任何东西,我们可以在恒定内存中完全做到这一点。
这将通过仅使用一个if语句遍历t
来实现:
// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
std::cout.tie(NULL);
return 0;
}();
// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <string>
using ValueType = std::uint_fast16_t;
static const struct Solution {
static const bool isSubsequence(
const std::string source,const std::string target
) {
const ValueType s_len = std::size(source);
const ValueType t_len = std::size(target);
ValueType s_index = 0;
for (ValueType t_index = 0; t_index < t_len && s_index < s_len; ++t_index) {
if (target[t_index] == source[s_index]) {
++s_index;
}
}
return s_index == s_len;
}
};