c++ - C++ 运行时错误:添加无符号偏移量?
问题描述
我写了以下内容来检查文本是否是回文,我在 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: undefined-behavior /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]))
r
可以变成负数,l
也可以变成>= 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
另一种方法是从with中删除所有非字母字符
std::erase_if(s, [](char c) { return !isalpha(c); });
并删除内部的while循环。
推荐阅读
- c - 我无法理解这个分段错误
- python-3.x - 为什么我收到“除了 ValueError”的语法错误
- ruby-on-rails - Button_to 带有类和按钮而不是输入类型提交
- javascript - 我想在上传到服务器 php mysql 之前将音频文件压缩到较小的大小
- shell - 如何根据每 100 个空行数拆分文件
- java - 如何删除白色背景以及如何添加棍子?
- java - 在 Android 的 Java 中使用 Microsoft Speech API 文本到语音?
- tensorflow - 二进制和多类分类代码更改
- javascript - 使用 jquery 根据 url 显示特定模式
- python - numpy where 在非排序数组上