Check if a String is a Palindrome in Java – 在Java中检查一个字符串是否是帕林陀罗

最后修改: 2018年 2月 14日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

In this article, we’re going to see how we can check whether a given String is a palindrome using Java.

在这篇文章中,我们将看到如何用Java检查一个给定的String是否是一个回文。

A palindrome is a word, phrase, number, or other sequences of characters which reads the same backward as forward, such as “madam” or “racecar”.

回文是指一个词、短语、数字或其他字符序列,其前后读法相同,如 “女士 “或 “赛车”。

2. Solutions

2.解决方案

In the following sections, we’ll look at the various ways of checking if a given String is a palindrome or not.

在下面的章节中,我们将看看检查一个给定的String是否是回文的各种方法。

2.1. A Simple Approach

2.1.一个简单的方法

We can simultaneously start iterating the given string forward and backward, one character at a time. If the there is a match the loop continues; otherwise, the loop exits:

我们可以同时开始向前和向后迭代给定的字符串,一次一个字符。如果有一个匹配的,循环继续;否则,循环退出。

public boolean isPalindrome(String text) {
    String clean = text.replaceAll("\\s+", "").toLowerCase();
    int length = clean.length();
    int forward = 0;
    int backward = length - 1;
    while (backward > forward) {
        char forwardChar = clean.charAt(forward++);
        char backwardChar = clean.charAt(backward--);
        if (forwardChar != backwardChar)
            return false;
    }
    return true;
}

2.2. Reversing the String

2.2.反转字符串

There are a few different implementations that fit this use case: we can make use of the API methods from StringBuilder and StringBuffer classes when checking for palindromes, or we can reverse the String without these classes.

有几种不同的实现适合这个用例:我们可以在检查重音时利用StringBuilderStringBuffer类的API方法,或者我们可以在没有这些类的情况下反转String

Let’s take a look at the code implementations without the helper APIs first:

让我们先看一下没有辅助API的代码实现。

public boolean isPalindromeReverseTheString(String text) {
    StringBuilder reverse = new StringBuilder();
    String clean = text.replaceAll("\\s+", "").toLowerCase();
    char[] plain = clean.toCharArray();
    for (int i = plain.length - 1; i >= 0; i--) {
        reverse.append(plain[i]);
    }
    return (reverse.toString()).equals(clean);
}

In the above snippet, we simply iterate the given String from the last character and append each character to the next character, all the way through to the first character thereby reversing the given String.

在上面的片段中,我们简单地从最后一个字符开始迭代给定的String ,并将每个字符附加到下一个字符,一直到第一个字符,从而反转给定的String。

Finally, we test for equality between the given String and reversed String.

最后,我们测试给定的字符串和反转的字符串之间是否相等。

The same behavior could be achieved using API methods.

使用API方法可以实现同样的行为。

Let’s see a quick demonstration:

让我们看一个快速示范。

public boolean isPalindromeUsingStringBuilder(String text) {
    String clean = text.replaceAll("\\s+", "").toLowerCase();
    StringBuilder plain = new StringBuilder(clean);
    StringBuilder reverse = plain.reverse();
    return (reverse.toString()).equals(clean);
}

public boolean isPalindromeUsingStringBuffer(String text) {
    String clean = text.replaceAll("\\s+", "").toLowerCase();
    StringBuffer plain = new StringBuffer(clean);
    StringBuffer reverse = plain.reverse();
    return (reverse.toString()).equals(clean);
}

In the code snippet, we invoke the reverse() method from the StringBuilder and StringBuffer API to reverse the given String and test for equality.

在代码片段中,我们从StringBuilderStringBuffer API中调用reverse()方法来反转给定的String并测试是否相等。

2.3. Using Stream API

2.3.使用Stream API

We can also use an IntStream to provide a solution:

我们也可以使用一个IntStream来提供一个解决方案。

public boolean isPalindromeUsingIntStream(String text) {
    String temp  = text.replaceAll("\\s+", "").toLowerCase();
    return IntStream.range(0, temp.length() / 2)
      .noneMatch(i -> temp.charAt(i) != temp.charAt(temp.length() - i - 1));
}

In the snippet above, we verify that none of the pairs of characters from each end of the String fulfills the Predicate condition.

在上面的片段中,我们验证来自String两端的字符对没有一个满足Predicate条件。

2.4. Using Recursion

2.4.使用递归

Recursion is a very popular method to solve these kinds of problems. In the example demonstrated we recursively iterate the given String and test to find out whether it’s a palindrome or not:

递归是解决这类问题的一种非常流行的方法。在所演示的例子中,我们递归地迭代给定的String,并测试出它是否是一个宫格。

public boolean isPalindromeRecursive(String text){
    String clean = text.replaceAll("\\s+", "").toLowerCase();
    return recursivePalindrome(clean,0,clean.length()-1);
}

private boolean recursivePalindrome(String text, int forward, int backward) {
    if (forward == backward) {
        return true;
    }
    if ((text.charAt(forward)) != (text.charAt(backward))) {
        return false;
    }
    if (forward < backward + 1) {
        return recursivePalindrome(text, forward + 1, backward - 1);
    }

    return true;
}

3. Conclusion

3.结论

In this quick tutorial, we saw how to find out whether a given String is a palindrome or not.

在这个快速教程中,我们看到了如何找出一个给定的String是否是一个调色板。

As always, the code examples for this article are available over on GitHub.

一如既往,本文的代码示例可在GitHub上获得