Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
class Solution {
public:
bool isPalindrome(string s) {
const int n = s.size();
if (n==0) {
return true;
}
int l = 0;
int r = n - 1;
while (l <= r) {
while (l < r && isalnum(s[l]) == false) {
l++;
}
while (r > l && isalnum(s[r]) == false) {
r--;
}
if (toupper(s[l]) != toupper(s[r])) {
return false;
}
l++;
r--;
}
return true;
}
};
本文介绍了一种算法,用于判断一个给定的字符串是否为回文,仅考虑字母和数字字符并忽略大小写。通过示例解释了如何排除非字母数字字符,并通过两个指针从两端向中间遍历的方法进行比较。
1864

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



