125. Valid Palindrome
125. Valid Palindrome
题目
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s
, return true
if it is a palindrome , or false
otherwise.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
Example 3:
Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
Constraints:
1 <= s.length <= 2 * 105
s
consists only of printable ASCII characters.
题目大意
如果一个短语在将所有大写字母转换为小写字母并删除所有非字母数字字符后,向前和向后读取相同的内容,则该短语是回文。字母数字字符包括字母和数字。
判断所给的字符串是否是有效的回文串。
解题思路
简单题,使用对撞指针挨个判断,如果左右指针不相等则立即返回 false,如果顺利遍历结束则返回 true。
代码
/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function (s) {
s = s.toLowerCase();
let left = 0;
let right = s.length - 1;
while (left <= right) {
if (!isChar(s[left])) {
left++;
} else if (!isChar(s[right])) {
right--;
} else if (s[left] !== s[right]) {
return false;
} else {
left++;
right--;
}
}
return true;
};
var isChar = function (i) {
return (i >= 'a' && i <= 'z') || (i >= '0' && i <= '9');
};
相关题目
- [234. 回文链表](./0234.md)
- [680. 验证回文串 II](https://leetcode.com/problems/valid-palindrome-ii)
- [2002. 两个回文子序列长度的最大乘积](https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences)
- [2108. 找出数组中的第一个回文字符串](https://leetcode.com/problems/find-first-palindromic-string-in-the-array)
- [🔒 Valid Palindrome IV](https://leetcode.com/problems/valid-palindrome-iv)