Search code examples
javastringbooleanstringbuilderpalindrome

String palindrome checker in java not working?


I am trying to write a program for these instructions:

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. https://leetcode.com/problems/valid-palindrome/

For some reason, the .reverse() in the last line doesn't reverse it. I've tried debugging by adding print statements and I see that the string DOES reverse earlier on. What is going on here? Please guide me!

public static boolean isPalindrome(String s) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        if (Character.isLetter(s.charAt(i))) {
            sb.append(s.charAt(i));
        }
    }
    String x = sb.reverse().toString();
    System.out.println(x);
    if (sb.length() == 0) 
        return true;
    else 
        return sb.toString().equals(x);
}

Solution

  • The problem is that reverse() changes the StringBuilder itself. So you are comparing the reverse, with the reverse again. Instead change your method to:

    String x = sb.toString();
    return sb.reverse().toString().equals(x);
    

    Which will compare the StringBuilder before reversing, with the reversed StringBuilder. Note that the if(sb.length == 0) is not necessary, as if it is empty, sb.reverse().toString().equals(x) will still return true.

    Also your search is case sensitive, when the problem statement says that it should match regardless of case. Change where you append to:

    if (Character.isLetter(s.charAt(i))) {               
         sb.append(Character.toLowerCase(s.charAt(i)));
    }
    

    Also you can take advantage of replaceAll and toLowerCase() to shorten your method to:

    public static boolean pali(String s) {
        String copy = s.toLowerCase().replaceAll("[^a-z]", "");
        return new StringBuilder(copy).reverse().toString().equals(copy);       
    }