简体   繁体   中英

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);
}

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);       
}

因为在第一次调用sb.reverse() sb更改了它的状态。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM