125. 验证回文串

如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后,短语正着读和反着读都一样。则可以认为该短语是一个 回文串 。

字母和数字都属于字母数字字符。

给你一个字符串 s,如果它是 回文串 ,返回 true ;否则,返回 false 。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const isTargetChar = (ascii: number) => {
return ascii >= 65 && ascii <= 90 || ascii >= 97 && ascii <= 122 || ascii >= 48 && ascii <= 57;
};

function isPalindrome(s: string): boolean {
let left = 0;
let right = s.length - 1;
while(left <= right) {
while(!isTargetChar(s.charCodeAt(left)) && left < s.length - 1) left++;
while(!isTargetChar(s.charCodeAt(right)) && right > left) right--;
if (left >= right) break;
if (s[left].toLowerCase() !== s[right].toLowerCase()) {
return false;
}
left++;
right--;
}
return true;
};