Thursday, May 29, 2014

LeetCode: 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.


If the size of the string is even, the start checking position will be the middle two chars. Else if it is odd, the start checking position is the middle char.

C++ Code:

/*
 * func: is_palindrome
 * goal: to test if the input string is a palindrome
 * @param s: input string
 * return: true or false
 */
/*
 * find the symmetry axis and then validate
 * complexity: time O(n), space O(n)
 */
bool is_palindrome(string s){
    string convert = "";
    //remove non-alphanumeric chars
    for(const char &ch : s){
        if(isalnum(ch)){
            convert += isupper(ch) ? (ch + 32) : ch;
        }
    }
    int s_length = convert.length();
    if(s_length <= 1){
        return true;
    }
    //Find symmetry axis
    int mid_left = 0;
    int mid_right = 0;
    if(s_length & 1){
        mid_left = s_length/2;
        mid_right = s_length/2;
    }else{
        mid_left = s_length/2 - 1;
        mid_right = s_length/2;
    }
    while(mid_left >= 0 && mid_right <s_length){
        if(convert[mid_left] == convert[mid_right]){
            --mid_left;
            ++mid_right;
        }else{
            return false;
        }
    }
    return true;
}

Python Code:

# func: to determine if the input string is a palindrome
# @param s: input string
# @return: True or False
def is_palindrome(s):
    str = ''.join(x.lower() for x in s if x.isalnum())
    if len(str) <= 1:
        return True
    if len(str) & 1:
        mid_left = len(str)/2
        mid_right = len(str)/2
    else:
        mid_left = len(str)/2 - 1
        mid_right = mid_left + 1

    while mid_left >= 0 and mid_right < len(str):
        if str[mid_left] == str[mid_right]:
            mid_left -= 1
            mid_right += 1
        else:
            return False
    return True

No comments:

Post a Comment