看似简单的问题总是非常容易出错!典型的测试用例非常关键!
问题: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:For the purpose of this problem, we define empty string as valid palindrome.
思路:主题思路非常简单,双指针就行了。但是细节上非常多。
要忽视空格和标点,要忽略大小写。
典型的测试用例:“ ”, ".,", "a.", ".a", "a0", "aA"
代码:
class Solution {
public:
bool isAlphanumeric(const char &a)
{
if((a >= 'a' && a <= 'z')||(a >= 'A' && a <= 'Z')||(a >= '0' && a <= '9'))
return true;
else
return false;
}
bool isEqual(const char &a, const char &b)
{
int x, y;
if(a>= 'a' && a <= 'z')
x = a - 'a';
else if(a>='A'&&a<='Z')
x = a - 'A';
else
x = a - '0' + 100; //将数字的范围和字母区别开!
if(b>= 'a' && b <= 'z')
y = b - 'a';
else if(b>='A'&&b<='Z')
y = b - 'A';
else
y = b - '0' + 100;
return (x == y);
}
bool isPalindrome(string s) {
int n = s.size();
if(n<2)
return true;
int left = 0;
int right = n- 1;
while(left < right)
{
while(left < right && !isAlphanumeric(s[left]))//时刻判断指针是否相遇!
left++;
while(left < right && !isAlphanumeric(s[right]))
right--;
if((!isAlphanumeric(s[left]))||(isEqual(s[left++],s[right--]))) //考虑全是非字符数字的情况
continue;
else
return false;
}
return true;
}
};