Valid Palindrome

Question (LC.125)

Given a string, verify whether it is a palindrome.

Example

("A man, a plan, a canal: Panama") => true
("Lol") => true
(" ,") => true

Only alphanumeric characters count. Not case-sensitive.

Analysis

L/R pointers. Have a skipping function and checking function that ignores the case.

Code

public boolean isPalindrome(String text) {
    if (text == null || text.length() <= 1) {
        return true;
    }
    int i = 0, j = text.length() - 1;
    while (i < j) {
        while (i < j && !Character.isLetterOrDigit(text.charAt(i))) {
            i++;
        }
        while (i < j && !Character.isLetterOrDigit(text.charAt(j))) {
            j--;
        }
        if (Character.toLowerCase(text.charAt(i)) != Character.toLowerCase(text.charAt(j))) {
            return false;
        }
        i++;
        j--;
    }
    return true;
}

Last updated