LeetCode Valid Palindrome

来源:互联网 发布:mysql root空密码登录 编辑:程序博客网 时间:2024/06/07 13:41

题目:

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 n = s.size();if (n == 0)return true;int i = 0, j = n-1;while (i < n && j >= 0) {if (isValid(s[i]) && isValid(s[j])) {if (isSame(s[i], s[j])) {i++, j--;continue;}else return false;}if (!isValid(s[i]))i++;if (!isValid(s[j]))j--;}return true;}private:bool isValid(char ch) {if ('0' <= ch && ch <= '9')return true;if ('a' <= ch && ch <= 'z')return true;if ('A' <= ch && ch <= 'Z')return true;return false;}bool isSame(char ch1, char ch2) {if (ch1 == ch2)return true;if ('a' <= ch1 && ch1 <= 'z')return ch1 - 'a' + 'A' == ch2;if ('A' <= ch1 && ch1 <= 'Z')return ch1 - 'A' + 'a' == ch2;return false;}};


0 0