【问题标题】:runtime error: addition of unsigned offset to 0x7ffeba23a6e0运行时错误:将无符号偏移量添加到 0x7ffeba23a6e0
【发布时间】:2020-08-31 07:59:32
【问题描述】:

这是我的代码,我在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

【问题讨论】:

  • 检查对“缓存”的访问:您可能超出了数组边界。使用嵌套向量或编写自定义内容来检查边界。
  • ij 从 0 开始,但你有 s[i-1]cache 有同样的问题。
  • 好的,谢谢,我理解错了,我忘了在if前面放else,否则会去索引越界。

标签: c++ c++11 subsequence


【解决方案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;
    }
};

【讨论】:

  • 是的,我只用这种方式解决了。但是存储缓存是我的第一种方法,一段时间后我找到了一个类似于你的解决方案。
【解决方案2】:

我解决了这个问题。错误是因为数组索引超出范围。 这是编辑部分:

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];
};

【讨论】:

    猜你喜欢
    • 2021-09-24
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多