Provide Best Programming Tutorials

Contents

# Question

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: falseSolution```

# Solution

```class Solution {
public static boolean isPalindrome(String s) {
if (s == null) return false;
if (s.length() == 0) return true;

s = s.toLowerCase().trim();
int i = 0;
int j = s.length() - 1;
while (i < j) {
while (i < j && !Character.isLetterOrDigit(s.charAt(i))) i++ ;
while (i < j && !Character.isLetterOrDigit(s.charAt(j))) j--;
if (s.charAt(i++) != s.charAt(j--)) return false;
}
return true;
}

public static void main(String[] args) {
isPalindrome("A man, a plan, a canal: Panama");
}
}```

Execution time: 18 ms, defeating 34.61% of users in Valid Palindrome’s Java submission

Memory consumption: 38.3 MB, defeating 78.33% of users in Valid Palindrome’s Java submission