Valid Palindrome

来源:互联网 发布:js权威指南第七版pdf 编辑:程序博客网 时间:2024/05/21 23:34

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.


Solution:

class Solution {public:    bool isPalindrome(string s) {        if(s.length() == 0) return true;        int left = 0, right = s.length() - 1;        while(left < right)        {            while(left < s.length() && !(s[left] >= '0' && s[left] <= '9') &&                  !(s[left] >= 'A' && s[left] <= 'Z') && !(s[left] >= 'a' && s[left] <= 'z')) left++;            while(right >= 0 && !(s[right] >= '0' && s[right] <= '9') &&                  !(s[right] >= 'A' && s[right] <= 'Z') && !(s[right] >= 'a' && s[right] <= 'z')) right--;            if(left >= right) break;            if(s[left] != s[right] && abs(s[left] - s[right]) != 32) break;            left++;            right--;        }        if(left >= right) return true;        else return false;    }};


0 0
原创粉丝点击