这题比较简单,写博客的主要目的是提醒自己注意一个细节问题。
题目
https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xne8id/
参考代码:
class Solution {
public:
bool isPalindrome(string s) {
int L=s.size();
if(L==1) return true;
for(int i=0; i<L; i++){
if( (s[i]>='A'&&s[i]<='Z') ) {s[i]+=32; continue;}
if( !((s[i]>='a'&&s[i]<='z')||(s[i]>='0'&&s[i]<='9')) )
s[i]=0;
}
int i=0,j=L-1;
while(true){
while(i<L && !s[i]) {i++;}
while(j>=0 && !s[j]) {j--;}
if(i>=j) return true;//过半了
if(s[i]!=s[j]) return false;
i++; j--;
}
return true;
}
};
测试结果:
在对数组或者链表等序列类型的变量进行遍历时,经常遇到内存访问溢出的error,在LeetCode中会提示Undefined Behavior(未定义行为),而本地编译器可能不会报错,甚至结果正确。
此题中出现访问溢出的代码是
while(!s[i] && i<L) {i++;}
while(!s[j] && j>=0) {j--;}
因为数组索引(i,j)判界语句放到了数组访问语句的后面,可能在边界处会出现越界访问的问题,导致运行时出错(Runtime Error)。具体来说就是如果i<L逻辑判断被触发(false),那前面的!s[i]一定会出现一次越界访问。
下面的代码块也出现了类似的问题:如果调换这两句,则在特殊情况下(数组大小L=2)会越界。
if(i>=j) return true;//过半了
if(s[i]!=s[j]) return false;