Is a Valid Palindrome with Java

0 min read 137 words

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;
    }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags