Valid Palindrome

Question (LC.125)

Analysis

A classic example of two (LR) pointers. So does two sum. There is also another type of two pointer (FS) ex.

Cycle in a linked list.

Code

public boolean isPalindrome(String s) {
    int i = 0, j = s.length() - 1;
    while (i < j) {
        // the tricky thing is to skip special chars and lower case letters
        while (i < j && !Character.isLetterOrDigit(s.charAt(i))) i++;
        while (i < j && !Character.isLetterOrDigit(s.charAt(j))) j--;
        if (Character.toLowerCase(s.charAt(i)) == Character.toLowerCase(s.charAt(j))) {
            i++;
            j--;
        } else return false;
    }
    return true;
}

results matching ""

    No results matching ""