125 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.
Special notes: empty string? upper/lower case? characters that are not letter?

Solution:

class Solution {
public:
    bool isValid(char c) {
        if ( c <= 'z' and c >= 'a' ) return true;
        if ( c <= '9' and c >= '0' ) return true;
        return false;
    }
    bool isPalindrome(string s) {
        int n = s.size();
        if ( n == 0 ) return true;
        int i = 0, j = n-1;
        while ( i <= j ) {
            char c1 = tolower(s[i]), c2 = tolower(s[j]);
            if ( not isValid(c1) ) {i++; continue;}
            if ( not isValid(c2) ) {j--; continue;}
            if ( c1 != c2 ) return false;
            i++;
            j--;
        }
        return true;
    }
};

Notes:

  1. the usage of "tolower"
  2. note the special case "0p".

results matching ""

    No results matching ""