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.

思路分析:
将字符串中的非数字字母字符跳过,大写全部转小写,然后从字符串两头向中间逼近,逐一进行比较。

C++参考示例:

class Solution
{
private:bool isAlphanumeric(char &ch){if (ch >= 'A' && ch <= 'Z'){ch += 32;return true;}if ((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')){return true;}return false;}public:bool isPalindrome(string s){size_t length = s.length();if (length <= 1){return true;}size_t i = 0;size_t j = length - 1;while (i < j){if (!isAlphanumeric(s[i])){i++;continue;}if (!isAlphanumeric(s[j])){j--;continue;}if (s[i] != s[j]){return false;}i++;j--;}return true;}
};

晒账截图!突然发现原来C#要比Java快这么多!
回文算法提交结果