【发布时间】: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 < s.length() && !isalpha(s[l])) -
""或"..."这样的输入会有问题。 -
正如声明的运行时错误,您将超出字符串的限制。您应该检查在每个
while循环中不会超过这些限制。