LeetCode 125. Valid Palindrome

Problem:

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:

Reading the question statement thoroughly is so important. I forgot about numeric values.

public class Solution {
    public boolean isPalindrome(String s) {
        if (s == null){
            return false;
        }
        if (s.length() <= 1) {
            return true;
        }
        s = s.toLowerCase();
        int low = 0;
        int high = s.length() - 1;
        while (low < high){
            char c1 = s.charAt(low);
            char c2 = s.charAt(high);
            boolean v1 = ('a' <= c1 && c1 <= 'z') || (48 <= c1 && c1 <= 57);
            boolean v2 = ('a' <= c2 && c2 <= 'z') || (48 <= c2 && c2 <= 57);
            if (!v1) {
                low++;
                continue;
            }
            if (!v2) {
                high--;
                continue;
            }
            if (c1 != c2) {
                return false;
            }
            low++;
            high--;
        }
        return true;
    }
}public class Solution {
    public boolean isPalindrome(String s) {
        if (s == null){
            return false;
        }
        if (s.length() <= 1) {
            return true;
        }
        s = s.toLowerCase();
        int low = 0;
        int high = s.length() - 1;
        while (low < high){
            char c1 = s.charAt(low);
            char c2 = s.charAt(high);
            boolean v1 = ('a' <= c1 && c1 <= 'z') || (48 <= c1 && c1 <= 57);
            boolean v2 = ('a' <= c2 && c2 <= 'z') || (48 <= c2 && c2 <= 57);
            if (!v1) {
                low++;
                continue;
            }
            if (!v2) {
                high--;
                continue;
            }
            if (c1 != c2) {
                return false;
            }
            low++;
            high--;
        }
        return true;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *