Wednesday, May 10, 2017

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



Solution:

Use two pointers to check character pairs from two sides to the centre.

If the character is not a number of alphabetical letters we skip it.

When we check if two characters are equal, we check if they are equal numbers, or same alphabetical letters without cases.

Notice if x and y are numbers, we cannot check them by taking the difference and see if it is equal to 'A' - 'a'.



Code:


public class Solution {
    public boolean isPalindrome(String s) {
        int i = 0;
        int j = s.length() - 1;
        while (i < j) {
            if (!isValid(s.charAt(i))) {
                i++;
                continue;
            }
            if (!isValid(s.charAt(j))) {
                j--;
                continue;
            }
            if (!isEqual(s.charAt(i), s.charAt(j))) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
    
    public boolean isValid(char c) {
        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
    }
    
    public boolean isEqual(char a, char b) {
        if (a >= '0' && a <= '9') {
            return a == b;
        }
        return (a == b) || (a == b - 'A' + 'a') || (b == a - 'A' + 'a');
    }
}