Thursday, April 10, 2014

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.
Solution:
Simple direct implementation, two pointers, start and end, when comparing, remember to remove all none alphabetic and numeric characters.
In C++, use isalnum() to determin if a char is a alphanumeric char
Code:
bool isPalindrome(string s) {

        if (s.size()==0)   {return true;}

        int st = 0;
        int ed = s.size()-1;

        while (st
            if (isalnum(s[st])==false){st++; continue;}
            if (isalnum(s[ed])==false){ed--; continue;}

            if (tolower(s[ed])!=tolower(s[st])){
                return false;
            }else{
                st++;
                ed--;
            }
        }

        return true;
}

No comments:

Post a Comment