首页 > 解决方案 > JAVA:如何确定输入是否为回文?

问题描述

请使用以下方法。

我正在尝试摆脱所有空格、标点符号并使所有内容都小写。然后我想看看字符串是否是回文(从正面和背面读取时相同。

我想不通。

public static void main(String[] args) {


        String word=null;
        String reverse="";
        Scanner console = new Scanner(System.in);

        System.out.print("Please enter a word or a phrase:");
        word = console.nextLine();

        word=word.replaceAll("\\s+",""); //removes white space
        word=word.replaceAll("[^a-zA-Z ]", ""); //removes all punctuation
        word=word.toLowerCase();


        for(int i=word.length()-1; i>=0; i--) {
        reverse +=word.charAt(i);


        }

        for(int i=0; i<word.length(); i++) {
            System.out.print(word);
        if(word.charAt(i) != reverse.charAt(i)) {
            System.out.println("Not a Palindrome");
        }else {
                System.out.println("Palindrome");```

标签: java

解决方案


首先,您可以将所有正则表达式组合成一个(首先使输入小写,然后消除所有不是小写字母的内容)。其次,您可以消除构建临时String以检查它是否是回文;因为您可以迭代中的字符word并检查正面和背面。喜欢,

System.out.print("Please enter a word or a phrase:");
String word = console.nextLine().toLowerCase().replaceAll("[^a-z]", "");
boolean palindrome = true;
for (int i = 0; i < word.length() / 2; i++) {
    if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
        palindrome = false;
        break;
    }
}
if (!palindrome) {
    System.out.println("Not a Palindrome");
} else {
    System.out.println("Palindrome");
}

如果您决定无论如何要反转word以实现效率较低的实施。使用StringBuilder,因为它可以在一行中完成(而且我认为它看起来更具可读性)。

System.out.print("Please enter a word or a phrase:");
String word = console.nextLine().toLowerCase().replaceAll("[^a-z]", "");
if (!new StringBuilder(word).reverse().toString().equals(word)) {
    System.out.println("Not a Palindrome");
} else {
    System.out.println("Palindrome");
}

推荐阅读