简体   繁体   English

如何在Java中获取字符串的回文

[英]How to get the palindrome of a string in Java

Ok.I know there are several other good procedures to check if a string is palindrome or not. 好的,我知道还有其他几种好的程序可以检查字符串是否是回文。
But I am trying this code.The problem is that since I am checking character by character, each time the character matches it prints out 但是我正在尝试这段代码。问题是由于我正在逐个字符地检查字符,因此每次字符匹配时都会打印出来
palindrome . 回文

But I want to print palindrome only once. 但是我只想打印一次回文

So is there a way so I can iterate through the loop completely and then the print statement is executed? 那么有没有一种方法可以让我完全遍历循环,然后执行print语句?

import java.util.Scanner;
public class Solution{
public static void main(String[] args){
    Scanner scan = new Scanner(System.in);
    String A = scan.next();

    for(int i =0;i<(A.length()/2);i++)
    {
        if(A.charAt(i)==A.charAt(A.length()-i-1))
            System.out.println("palindrome");
        else
            System.out.println("not palindrome");

    }
  }
}

I would keep a boolean flag (defaulted to true ) and set to false if it isn't. 我会保持一个boolean标志(默认为true ),并设置为false ,如果它不是。 Then check your flag after the loop. 然后在循环后检查您的标志。 Something like, 就像是,

boolean palindrome = true;
for(int i = 0; i < (A.length() / 2); i++)
{
    if (A.charAt(i) != A.charAt(A.length() - i - 1)) {
        palindrome = false;
        break;
    }
}
if (palindrome) {
     System.out.println("palindrome");
} else {
    System.out.println("not palindrome");
}

You could write the last part with the ternary (or conditional operator ? : ) like 您可以使用三元 (或条件运算符? : :)来编写最后一部分

System.out.println(palindrome ? "palindrome" : "not palindrome");

And , you could replace the loop with StringBuilder.reverse() like 并且 ,您可以使用StringBuilder.reverse() 代替循环,例如

boolean palindrome = new StringBuilder(A).reverse().toString().equals(A);

So, it could be a one liner like 因此,它可能是一个像

System.out.println(new StringBuilder(A).reverse().toString().equals(A) 
       ? "palindrome" : "not palindrome");

You should track if the string is still valid or not, for example: 您应该跟踪字符串是否仍然有效,例如:

boolean palin = true;
for(int i =0 ; i < A.length()/2 ; i++) {
    if(A.charAt(i)!=A.charAt(A.length()-i-1)) {
        palin = false;
        break;
    }
}

if(palin) System.out.println("Is Palindrome");
else System.out.println("Is Not a Palindrome");

In your code, you check front-half characters against back-half characters, and print palindrome / not palindrome on each character. 在您的代码中,您将前半个字符与后半个字符进行比较,并在每个字符上打印palindrome / not palindrome

Instead, you should loop through the whole string, determine if the whole string is a palindrome or not, and then print once at the very end. 相反,您应该遍历整个字符串,确定整个字符串是否是回文,然后在最后打印一次。

Here is a straightforward way to fix your code: 这是修复代码的直接方法:

// At the start, we assume the string is a palindrome.
boolean palin = true;

// We loop through the characters, looking for evidence to contradict our
// assumption. Once palin becomes false, it can never become true again.
for(int i =0;i<(A.length()/2);i++)
{
    if(A.charAt(i)!=A.charAt(A.length()-i-1))
        palin = false;
}

// Now the Boolean variable tells us the answer we want.
if (palin) System.out.println("palindrome");
else System.out.println("not palindrome");

I like all the responses given above. 我喜欢上面给出的所有回复。 I however, think that your code will have the following issues: 1. It will consider a single character a palindrome. 但是,我认为您的代码将存在以下问题:1.将单个字符视为回文。
2. It will not recognize Rotor and rotoR as palindromes. 2.它不会将Rotor和rotoR识别为回文。

I have also added code for you to benchmark your method against your file. 我还为您添加了代码,以针对您的文件对方法进行基准测试。 I think it is very costly. 我认为这非常昂贵。 So reconsider using better algorithm. 因此,请重新考虑使用更好的算法。

package algorithms;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

public class PalindromeAnalysis {

public static void main(String[] args) {
    Path p1 = Paths.get("/Users/droy/var/palindrome.txt");

    Scanner scan = null;
    try {
        scan = new Scanner(p1);
    } catch (IOException e) {
        e.printStackTrace();
    } 

    long st1 = System.currentTimeMillis();
    while (scan.hasNext()){
        String A = scan.next();
        boolean isPalindrome = true;
        try {
                if (A.length() <= 2) throw new Exception("Is not a Palindrome");

                for(int i =0; i<(A.length()/2);i++)
                { 
                    if (A.toUpperCase().charAt(i) != A.toUpperCase().charAt(A.length()-i-1)){
                        throw new Exception("Is not a Palindrome");
                    }
                }
        }
        catch (Exception e) {
            isPalindrome = false;
        }

        if (isPalindrome){
            System.out.println("This is Palindrome : " + A);
        }
        else {
            System.out.println("This is not Palindrome" + A);
        }
    }

    long et1 = System.currentTimeMillis();
    System.out.println("Time it took was:" + (et1 - st1) + " ms");
}
}

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

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