给定一个字符串 s
,验证 s
是否是 回文串 ,只考虑字母和数字字符,可以忽略字母的大小写。
本题中,将空字符串定义为有效的 回文串 。
示例 1:
输入: s = "A man, a plan, a canal: Panama"
输出: true
解释:"amanaplanacanalpanama" 是回文串
示例 2:
输入: s = "race a car"
输出: false
解释:"raceacar" 不是回文串
提示:
1 <= s.length <= 2 * 105
- 字符串
s
由 ASCII 字符组成
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean isPalindrome(String s) {
if (s == null || s.length() == 0) {
return true;
}
int start = -1;
int end = s.length();
while (start < end) {
start = getNextIndex(s, start, true);
end = getNextIndex(s, end, false);
if (start >= end) {
break;
}
char startCh = s.charAt(start);
char endCh = s.charAt(end);
if (!isEqualChar(startCh, endCh)) {
return false;
}
}
return true;
}
boolean isEqualChar(char c1, char c2) {
int i1 = -1;
int i2 = -1;
if ('a' <= c1 && c1 <= 'z') {
i1 = c1 - 'a';
}
if ('A' <= c1 && c1 <= 'Z') {
i1 = c1 - 'A';
}
if ('a' <= c2 && c2 <= 'z') {
i2 = c2 - 'a';
}
if ('A' <= c2 && c2 <= 'Z') {
i2 = c2 - 'A';
}
if (i1 == -1) {
i1 = c1;
}
if (i2 == -1) {
i2 = c2;
}
return i1 == i2;
}
private int getNextIndex(String s, int curIndex, boolean leftToRight) {
if (leftToRight) {
curIndex++;
} else {
curIndex--;
}
if (curIndex < 0) {
return curIndex;
}
if (curIndex >= s.length()) {
return curIndex;
}
char ch = s.charAt(curIndex);
if (('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9')) {
return curIndex;
}
return getNextIndex(s, curIndex, leftToRight);
}
}
//leetcode submit region end(Prohibit modification and deletion)