125. Valid Palindrome*
https://leetcode.com/problems/valid-palindrome/
题目描述
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
C++ 实现 1
思路仍然是对撞指针. 这里还要借用标准库 <cctype> 中的 std::isalnum 判断 alphanumeric 字符, 另外使用 std::tolower 将字符转换为小写. 这里注意 std::tolower 也可以直接作用在 digit 上.
class Solution {
public:
bool isPalindrome(string s) {
int l = 0, r = s.size() - 1;
while (l <= r) {
while (l <= r && !std::isalnum(s[l])) ++ l;
while (l <= r && !std::isalnum(s[r])) -- r;
if (l > r) break;
if (std::tolower(s[l++]) != std::tolower(s[r--])) return false;
}
return true;
}
};
381




被折叠的 条评论
为什么被折叠?



