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.

#include <stdlib.h>
#include <stdio.h>
#include <string>
using std::string;

class Solution {
    public:
        bool isAlphaNumber(char & c)
        {
            if (c >= '0' && c <= '9')
            {
                return true;
            }
            if (c >= 'a' && c <= 'z')
            {
                return true;
            }
            if (c >= 'A' && c <= 'Z')
            {
                c += 'a' - 'A';
                return true;
            }
            return false;
        }
        bool isPalindrome(string s) {
            // Start typing your C/C++ solution below
            //         // DO NOT write int main() function
            //                 
            if (s.empty())
            {
                return true;
            }
            int i = 0, j = s.size() - 1;
            char a,b;
            while(i < s.size() && j >= 0){
                a = s.at(i);
                b = s.at(j);
                if (!isAlphaNumber(a))
                {
                    i++;
                    continue;
                }
                if (!isAlphaNumber(b))
                {
                    j--;
                    continue;
                }
                if (a == b)
                {
                    i++;
                    j--;
                }else
                {
                    return false;
                }
            }
            //if (i + j != s.size())
            //{
            //    return false;
            //}else
            {
                return true;
            }
        }
};

 

posted @ 2013-02-27 22:44  一只会思考的猪  阅读(189)  评论(0编辑  收藏  举报