Friday, July 10, 2015

Valid Palindrome | Leetcode

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: Maintain two pointers, one pointing to the beginning of the string, and the other pointing to the end of the string. Advance first pointer to a position where it is an alpha-numeric character. Retreat last pointer to a position where it is an alpha-numeric character. If the character at the first pointer is not the same as the character at the last pointer, then return false. Repeat until done (first >= last). Return true if you did not discover any inequalities.
public class Solution {
    public boolean isPalindrome(String s) {
        int first = 0;
        int last = s.length() - 1;
        int ch1, ch2;
        
        while (first < last) {
            while (true) {
                ch1 = s.charAt(first++);
                if (Character.isLetterOrDigit(ch1)) break;
                if (first >= last) return true;
            }
            
            while (true) {
                ch2 = s.charAt(last--);
                if (Character.isLetterOrDigit(ch2)) break;
                if (first >= last) return true;
            }
            
            if (Character.toUpperCase(ch1) != Character.toUpperCase(ch2)) {
                return false;
            }
        }
        
        return true;
    }
}

No comments: