Is a Valid Palindrome with Java

The challenge

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

Constraints:

  • s consists only of printable ASCII characters.

The solution in Java

class Solution { // take in a String public boolean isPalindrome(String s) { // remove all non-alphanumeric characters and lowercase everything s = s.replaceAll("\\P{Alnum}", "").toLowerCase(); // loop through the String for (int i=0; i<s.length(); i++) { // if the beginning and last characters don't match, return false // also walk in both directions and do the same if (s.charAt(i)!=s.charAt(s.length()-i-1)) return false; } // return true if we get here return true; } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments