problem:
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.
Two Pointers String
题意:判断一个字符串是否为有效的回文字符串,只考虑数字字符和大小写字符,其他符号不考虑。
thinking:
(1)采用双指针,首尾指针往中间遍历
(2)首先对字符过滤,排除数字字符和大小写字符之外的符号
(2)字符相等或者只是大小写只差,两个指针都往中间前进一步
code:
class Solution {
public:
bool isPalindrome(string s) {
int n=s.size();
if(n==0)
return true;
int i=0;
int j=n-1;
while(i<=j)
{
char a=s.at(i);
char b=s.at(j);
if(a<'0'||(a>'9'&&a<'A')||a>'z'||(a>'Z'&&a<'a'))
{
i++;
continue;
}
if(b<'0'||(b>'9'&&b<'A')||b>'z'||(b>'Z'&&b<'a'))
{
j--;
continue;
}
if(a==b || abs(a-b)=='a'-'A')
{
i++;
j--;
}
else
return false;
}
return true;
}
};