简体   繁体   English

Java中的字符串回文检查器不起作用?

[英]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. 注意:针对此问题,我们将空String定义为有效回文。 https://leetcode.com/problems/valid-palindrome/ https://leetcode.com/problems/valid-palindrome/

For some reason, the .reverse() in the last line doesn't reverse it. 由于某种原因,最后一行中的.reverse()不会将其反转。 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. 问题是reverse()更改StringBuilder本身。 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 . 它将反转之前StringBuilder与反转的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. 请注意, if(sb.length == 0)不是必需的,就好像它是空的一样, sb.reverse().toString().equals(x)仍将返回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: 您还可以利用replaceAlltoLowerCase()将方法缩短为:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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