Wednesday, April 23, 2014

[LeetCode] Valid Palindrome

Problem Statement (link):
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.
Analysis:
We compare the to chars from head and tail of the string, if they are the same, we proceed on checking the next char pair, otherwise, we return false.

Note that we need to check if the chars are valid chars before comparison.

This algorithm gives us O(n) time complexity.

Code:
class Solution {
public:
    bool isPalindrome(string s) {
        if (s.empty()) return true;
        int len=s.length();
       
        int head=0, tail=len-1;
        while (tail>=head) {
            // Skip invalid chars
            if (!isValid(s[head])) {
                head++;
                continue;
            }
            if (!isValid(s[tail])) {
                tail--;
                continue;
            }

            if (!isEqual(s[head], s[tail])) return false;
            head++; tail--;
        }
        return true;
    }
       
    bool isEqual(char c1, char c2) {
        if (c1==c2 || c1-c2=='A'-'a' || c1-c2=='a'-'A')
            return true;
        return false;
    }
    bool isValid(char c1) {
        if ((c1-'0'>=0 && c1-'0'<10) || (c1-'a'>=0 && c1-'a'< 26) || (c1-'A'>=0 && c1-'A'<26))
            return true;
        return false;
    }
};

No comments:

Post a Comment