Monday, November 25, 2013

LeetCode Problem : Valid Palindrome

Problem



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.

Code

bool isAlphaNum(char c){
    return ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'));
}
bool isPalindrome(string s) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    int n = s.size();
    if(n < 2)
        return true;
    std::transform(s.begin(), s.end(), s.begin(), ::tolower);
    int i = 0, j = n - 1;
    while(i < j){
        while(i < j && !isAlphaNum(s[i]))
            ++i;
        while(i < j && !isAlphaNum(s[j]))
            --j;
        if(j <= i)
            break;
        if(s[i] != s[j])
            return false;
        ++i;
        --j;
    }
    return true;
}


No comments:

Post a Comment