【LeetCode】 125 验证回文串
解题思路:
1 哦 看呐,这是我们的老朋友双指针,3Sum这道题也是用这个来做的。设定两个指针从前后分别向中间遍历,验证遇到的对应位置的字符是不是相等。
2 需要注意:统一大小写的时候别用Character的API toUpperCase,耗时较多,直接x-=32即可;同时注意不可以x = x - 32,会报类型转换错误;
代码:
class Solution {
public boolean isPalindrome(String s) {
s = s.trim();
char[] c = s.toCharArray();
int left;
int right;
for (left = 0, right = s.length() - 1;left <= right;){
//非字母数字则不处理
//left找字母或者数字
while (left < s.length() && !isValidChar(c[left]))
left++;
//right找字母或数字
while (right >= 0 && !isValidChar(c[right]))
right--;
if (left == s.length() && right == -1)
return true;
//大小写统一
if(c[left]>='a'){
c[left]-=32;
}
if(c[right]>='a'){
c[right]-=32;
}
//判断是否相同
if (c[left] != c[right])
return false;
else {
left++; right--;
}
}
return true;
}
private boolean isValidChar(char c){
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9');
}
}