Wednesday, February 18, 2015

LeetCode [125] Valid Palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
    bool isValid(char c){
        return (c>='a'&&c<='z')||(c>='A'&&c<='Z')||isdigit(c);
    }
    bool isEqual(char a, char b){
        int diff = abs('a'-'A');
        return a==b||(!isdigit(a)&&!isdigit(b)&&abs(a-b)==diff);
    }
public:
    bool isPalindrome(string s) {
        int n = s.size(), i = 0, j = n-1;
        while(i<=j){
            if(!isValid(s[i])){
                i++;
            }else if(!isValid(s[j])){
                j--;
            }else if(isEqual(s[i], s[j])){
                i++; j--;
            }else{
                return false;
            } 
        }
        return true;
    }
};

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
    #define isA(c) ((c>='a'&&c<='z')||(c>='A'&&c<='Z'))
    #define isAN(c) (isA(c)||(c>='0'&&c<='9'))
    #define isEqual(c1,c2) (isA(c1)&&isA(c2)&&abs(c1-c2)==32||c1==c2)
public:
    bool isPalindrome(string s) {
        int n = s.size(), l = 0, r = n-1;
        while(l<r){
            while(l<r && !isAN(s[l])) l++;
            while(l<r && !isAN(s[r])) r--;
            if(l<r && !isEqual(s[l], s[r])) return false;
            l++;
            r--;
        }
        return true;
    }
};

No comments:

Post a Comment