125. Valid Palindrome

2019/10/22 Leetcode

125. Valid Palindrome

Tags: ‘Two Pointers’, ‘String’

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false

Solution

O(n) time O(1) space 82% 96%

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

Search

    Table of Contents