# [LeetCode] Valid Palindrome 验证回文字符串

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) {
int left = 0, right = s.size() - 1 ;
while (left < right) {
if (!isAlphaNum(s[left])) ++left;
else if (!isAlphaNum(s[right])) --right;
else if ((s[left] + 32 - 'a') %32 != (s[right] + 32 - 'a') % 32) return false;
else {
++left; --right;
}
}
return true;
}
bool isAlphaNum(char &ch) {
if (ch >= 'a' && ch <= 'z') return true;
if (ch >= 'A' && ch <= 'Z') return true;
if (ch >= '0' && ch <= '9') return true;
return false;
}
};

class Solution {
public:
bool isPalindrome(string s) {
int left = 0, right = s.size() - 1 ;
while (left < right) {
if (!isalnum(s[left])) ++left;
else if (!isalnum(s[right])) --right;
else if ((s[left] + 32 - 'a') %32 != (s[right] + 32 - 'a') % 32) return false;
else {
++left; --right;
}
}
return true;
}
};

https://discuss.leetcode.com/topic/5581/here-s-a-clean-c-solution/2

https://discuss.leetcode.com/topic/25405/my-three-line-java-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2014-10-17 04:09  Grandyang  阅读(21236)  评论(5编辑  收藏  举报