Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leetcode Valid Palindrome Question Problem Debugging [duplicate]

I'm struggling to understand what's wrong with my code for this Leetcode problem.

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

Right now, I am passing 108/476 cases, and I am failing this test: "A man, a plan, a canal: Panama".

Here is my code, please help me identify the problem!

class Solution {
public boolean isPalindrome(String s) {

    if (s.isEmpty()) return true;

    s.replaceAll("\\s+","");

    int i = 0;
    int j = s.length() - 1;

    while (i <= j) {

        if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) {

            return false;

        }

        i++;
        j--;

    }

    return true;

}
}
like image 970
Alireza Firouzja Avatar asked Aug 16 '26 23:08

Alireza Firouzja


1 Answers

Your replaceAll method is incorrect

Your replaceAll method currently only removes spaces. It should remove all the special characters and keep only letters. If we use the regex way like you do, this is (one of) the best regex to use:

s = s.replaceAll("[^a-zA-Z]+","");

You could be tempted to use the \W (or [^\w]) instead, but this latest regex matches [a-zA-Z0-9_], including digits and the underscore character. Is this what you want? then go and use \W instead. If not, stick to [^a-zA-Z].

If you want to match all the letters, no matter the language, use the following:

s = s.replace("\\P{L}", "");

Note that you could shorten drastically your code like this, although it's definitely not the fastest:

class Solution {
  public boolean isPalindrome(String s) {
    s = s.replaceAll("\\P{L}", "");
    return new StringBuilder(s).reverse().toString().equalsIgnoreCase(s);
  }
}
like image 196
Olivier Grégoire Avatar answered Aug 18 '26 13:08

Olivier Grégoire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!