🌗 125. 验证回文串
2022年10月10日
- algorithm
🌗 125. 验证回文串
难度: 🌗
问题描述
解法
class Solution {
public boolean isPalindrome(String s) {
// 思路:
// 双指针
int len = s.length();
if(len <= 1) {
return true;
}
// len >= 2
int left = 0;
int right = len - 1;
int diff = Math.abs('A' - 'a');
while(left < right) {
while(left < right && !isDigit(s.charAt(left)) && !isValid(s.charAt(left))) {
left ++;
}
while(left < right && !isDigit(s.charAt(right)) && !isValid(s.charAt(right))) {
right --;
}
if(left == right) {
return true;
} else {
// left < right
char a = s.charAt(left);
char b = s.charAt(right);
if(isDigit(a) && a == b) {
left ++;
right --;
} else if(isValid(a) && isValid(b)) {
if(a == b || Math.abs(a - b) == diff) {
left ++;
right --;
} else {
return false;
}
} else {
return false;
}
}
}
return true;
}
private boolean isValid(char c) {
if(c >= 'a' && c <= 'z') {
return true;
}
if(c >= 'A' && c <= 'Z') {
return true;
}
return false;
}
private boolean isDigit(char c) {
if(c >= '0' && c <= '9') {
return true;
}
return false;
}
}