【问题标题】:C++ runtime error: addition of unsigned offset?C++ 运行时错误:添加无符号偏移量?
【发布时间】:2021-05-22 08:01:33
【问题描述】:

我写了以下代码来检查文本是否是回文,我在 leetcode 上运行它,我得到了错误:

class Solution {
public:
    bool isPalindrome(string s) {
        int l=0,r=s.length()-1;
        while(l<r)
        {
            while (!isalpha(s[r]))
            {
                --r;
            }
            while (!isalpha(s[l]))
            {
                ++l;
            }
            if (tolower(s[r])!=tolower(s[l]))
                return false;
            --r;
            ++l;
        }
        return true;
    }
};

第 1061 行:字符 9:运行时错误:将无符号偏移量添加到 0x7ffc7cc10880 溢出到 0x7ffc7cc1087f (basic_string.h) 摘要: UndefinedBehaviorSanitizer:未定义行为 /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/basic_string.h:1070:9

我的代码有什么问题?

【问题讨论】:

  • 你在这里越界了:while (!isalpha(s[r])) 和这里while (!isalpha(s[l]))。您应该添加一些检查,例如 while (l &lt; s.length() &amp;&amp; !isalpha(s[l]))
  • """..." 这样的输入会有问题。
  • 正如声明的运行时错误,您将超出字符串的限制。您应该检查在每个 while 循环中不会超过这些限制。

标签: c++ string c++11


【解决方案1】:

你在这里越界了:

while (!isalpha(s[r]))

这里

while (!isalpha(s[l]))

r 可以变成负数,l 可以变成&gt;= s.length()

您应该添加一些检查,例如

while (l < r && !isalpha(s[r]))

while (l < r && !isalpha(s[l]))

这一行同样的问题

if (tolower(s[r])!=tolower(s[l]))

这应该是

if (l < r && tolower(s[r])!=tolower(s[l]))

不同的方法 (C++20)

另一种方法是删除 s 中的所有非字母字符

std::erase_if(s, [](char c) { return !isalpha(c); });

并删除内部的 while 循环。

【讨论】:

  • 但如果输入为“,”,检查将使解决方案无效
  • @calc 但是如果没有检查,您的代码会导致未定义的行为。你对s[-1]s[s.length() + 2] 有什么期望?这正是s = "123"s = ""s = "," 等输入代码中的问题。你会越界,因为你不检查界限。 "," 是不是回文?
【解决方案2】:

我认为您非常接近解决方案。这里的陷阱是:

  • 您在循环中多次修改循环控制变量
  • (因此)您在更改其值后使用循环控制变量而无需进一步检查。

解决此类问题的简单方法是每次迭代都执行一个操作。您只需使用“else”即可实现此目的。

class Solution {
public:
    bool isPalindrome(string s) {
        int l=0,r=s.length()-1;
        while(l<r)
        {
            if(!isalpha(s[r]))
            {
                --r;
            }
            else if(!isalpha(s[l]))
            {
                ++l;
            }
            else if (tolower(s[r])!=tolower(s[l]))
            {
                return false;
            }
            else
            {
                --r;
                ++l;
            }
        }
        return true;
    }
};

【讨论】:

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