Java 检查回文字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4138827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:01:01  来源:igfitidea点击:

Check string for palindrome

javaarraysstringcharpalindrome

提问by Upvote

A palindromeis a word, phrase, number or other sequence of units that can be read the same way in either direction.

回文是单词,短语,数字或的单元的其它序列可以读取在任一方向的方式相同。

To check whether a word is a palindrome I get the char array of the word and compare the chars. I tested it and it seems to work. However I want to know if it is right or if there is something to improve.

为了检查一个词是否是回文,我得到了这个词的字符数组并比较了字符。我测试了它,它似乎有效。但是我想知道它是否正确或者是否有需要改进的地方。

Here is my code:

这是我的代码:

public class Aufg1 {
    public static void main(String[] args) {
        String wort = "reliefpfpfeiller";
        char[] warray = wort.toCharArray(); 
        System.out.println(istPalindrom(warray));       
    }

    public static boolean istPalindrom(char[] wort){
        boolean palindrom = false;
        if(wort.length%2 == 0){
            for(int i = 0; i < wort.length/2-1; i++){
                if(wort[i] != wort[wort.length-i-1]){
                    return false;
                }else{
                    palindrom = true;
                }
            }
        }else{
            for(int i = 0; i < (wort.length-1)/2-1; i++){
                if(wort[i] != wort[wort.length-i-1]){
                    return false;
                }else{
                    palindrom = true;
                }
            }
        }
        return palindrom;
    }
}

采纳答案by dcp

Why not just:

为什么不只是:

public static boolean istPalindrom(char[] word){
    int i1 = 0;
    int i2 = word.length - 1;
    while (i2 > i1) {
        if (word[i1] != word[i2]) {
            return false;
        }
        ++i1;
        --i2;
    }
    return true;
}

Example:

例子:

Input is "andna".
i1 will be 0 and i2 will be 4.

输入是“andna”。
i1 为 0,i2 为 4。

First loop iteration we will compare word[0]and word[4]. They're equal, so we increment i1 (it's now 1) and decrement i2 (it's now 3).
So we then compare the n's. They're equal, so we increment i1 (it's now 2) and decrement i2 (it's 2).
Now i1 and i2 are equal (they're both 2), so the condition for the while loop is no longer true so the loop terminates and we return true.

第一次循环迭代我们将比较word[0]word[4]。它们相等,所以我们增加 i1(现在是 1)并减少 i2(现在是 3)。
所以我们然后比较n。它们相等,所以我们增加 i1(现在是 2)并减少 i2(现在是 2)。
现在 i1 和 i2 相等(它们都是 2),所以 while 循环的条件不再为真,所以循环终止,我们返回真。

回答by Casey

public class Palindromes {
    public static void main(String[] args) {
         String word = "reliefpfpfeiller";
         char[] warray = word.toCharArray(); 
         System.out.println(isPalindrome(warray));       
    }

    public static boolean isPalindrome(char[] word){
        if(word.length%2 == 0){
            for(int i = 0; i < word.length/2-1; i++){
                if(word[i] != word[word.length-i-1]){
                    return false;
                }
            }
        }else{
            for(int i = 0; i < (word.length-1)/2-1; i++){
                if(word[i] != word[word.length-i-1]){
                    return false;
                }
            }
        }
        return true;
    }
}

回答by Greg

You can check if a string is a palindrome by comparing it to the reverse of itself:

您可以通过将字符串与自身的反向进行比较来检查字符串是否为回文:

public static boolean isPalindrome(String str) {
    return str.equals(new StringBuilder(str).reverse().toString());
}

or for versions of Java earlier than 1.5,

或者对于早于 1.5 的 Java 版本,

public static boolean isPalindrome(String str) {
    return str.equals(new StringBuffer().append(str).reverse().toString());
}

EDIT:@FernandoPelliccioni provided a very thorough analysisof the efficiency (or lack thereof) of this solution, both in terms of time and space. If you're interested in the computational complexity of this and other possible solutions to this question, please read it!

编辑:@FernandoPelliccioni 提供对该解决方案在时间和空间方面的效率(或缺乏效率)的非常彻底的分析。如果您对此问题的计算复杂度和其他可能的解决方案感兴趣,请阅读它!

回答by Marc

I worked on a solution for a question that was marked as duplicate of this one. Might as well throw it here...

我为一个被标记为这个问题的重复问题研究了一个解决方案。还不如扔这里...

The question requested a single line to solve this, and I took it more as the literary palindrome - so spaces, punctuation and upper/lower case can throw off the result.

这个问题要求用一行来解决这个问题,我更多地把它当作文学回文——所以空格、标点符号和大写/小写可能会影响结果。

Here's the ugly solution with a small test class:

这是带有小型测试类的丑陋解决方案:

public class Palindrome {
   public static boolean isPalendrome(String arg) {
         return arg.replaceAll("[^A-Za-z]", "").equalsIgnoreCase(new StringBuilder(arg).reverse().toString().replaceAll("[^A-Za-z]", ""));
   }
   public static void main(String[] args) {
      System.out.println(isPalendrome("hiya"));
      System.out.println(isPalendrome("star buttons not tub rats"));
      System.out.println(isPalendrome("stab nail at ill Italian bats!"));
      return;
   }
}

Sorry that it is kind of nasty - but the other question specified a one-liner.

抱歉,这有点令人讨厌 - 但另一个问题指定了一个单线。

回答by user2039532

public class palindrome {
public static void main(String[] args) {
    StringBuffer strBuf1 = new StringBuffer("malayalam");
    StringBuffer strBuf2 = new StringBuffer("malayalam");
    strBuf2.reverse();


    System.out.println(strBuf2);
    System.out.println((strBuf1.toString()).equals(strBuf2.toString()));
    if ((strBuf1.toString()).equals(strBuf2.toString()))
        System.out.println("palindrome");
    else
        System.out.println("not a palindrome");
}

}

}

回答by Andrew Mao

A concise version, that doesn't involve (inefficiently) initializing a bunch of objects:

一个简洁的版本,不涉及(低效)初始化一堆对象:

boolean isPalindrome(String str) {    
    int n = str.length();
    for( int i = 0; i < n/2; i++ )
        if (str.charAt(i) != str.charAt(n-i-1)) return false;
    return true;    
}

回答by ARAVIN

Try this out :

试试这个:

import java.util.*;
    public class str {

        public static void main(String args[])
        {
          Scanner in=new Scanner(System.in);
          System.out.println("ENTER YOUR STRING: ");
          String a=in.nextLine();
          System.out.println("GIVEN STRING IS: "+a);
          StringBuffer str=new StringBuffer(a);
          StringBuffer str2=new StringBuffer(str.reverse());
          String s2=new String(str2);
          System.out.println("THE REVERSED STRING IS: "+str2);
            if(a.equals(s2))    
                System.out.println("ITS A PALINDROME");
            else
                System.out.println("ITS NOT A PALINDROME");
            }
    }

回答by Francisco Gutiérrez

Go, Java:

去吧,爪哇:

public boolean isPalindrome (String word) {
    String myWord = word.replaceAll("\s+","");
    String reverse = new StringBuffer(myWord).reverse().toString();
    return reverse.equalsIgnoreCase(myWord);
}

isPalindrome("Never Odd or Even"); // True
isPalindrome("Never Odd or Even1"); // False

回答by gogobebe2

I'm new to java and I'm taking up your question as a challenge to improve my knowledge.

我是 Java 新手,我将您的问题作为提高我知识的挑战。

import java.util.ArrayList;
import java.util.List;

public class PalindromeRecursiveBoolean {

    public static boolean isPalindrome(String str) {

        str = str.toUpperCase();
        char[] strChars = str.toCharArray();

        List<Character> word = new ArrayList<>();
        for (char c : strChars) {
            word.add(c);
        }

        while (true) {
            if ((word.size() == 1) || (word.size() == 0)) {
                return true;
            }
            if (word.get(0) == word.get(word.size() - 1)) {
                word.remove(0);
                word.remove(word.size() - 1);
            } else {
                return false;

            }

        }
    }
}
  1. If the string is made of no letters or just one letter, it is a palindrome.
  2. Otherwise, compare the first and last letters of the string.
    • If the first and last letters differ, then the string is not a palindrome
    • Otherwise, the first and last letters are the same. Strip them from the string, and determine whether the string that remains is a palindrome. Take the answer for this smaller string and use it as the answer for the original string then repeat from 1.
  1. 如果字符串没有字母或只有一个字母,则它是回文。
  2. 否则,比较字符串的第一个和最后一个字母。
    • 如果第一个和最后一个字母不同,则该字符串不是回文
    • 否则,第一个和最后一个字母是相同的。从字符串中剥离它们,并确定剩余的字符串是否为回文。取这个较小字符串的答案并将其用作原始字符串的答案,然后从1重复。

回答by Amandeep Dhanjal

public boolean isPalindrome(String abc){
    if(abc != null && abc.length() > 0){
        char[] arr = abc.toCharArray();
        for (int i = 0; i < arr.length/2; i++) {
            if(arr[i] != arr[arr.length - 1 - i]){
                return false;
            }
        }
        return true;
    }
    return false;
}