Java如何确定字符串是否是回文?
此代码检查字符串,以确定它是否是回文。回文是一个单词,词组或序列,向后读与向后读相同。
package org.nhooo.example.lang; public class PalindromeChecker { public static void main(String[] args) { String text = "Sator Arepo Tenet Opera Rotas"; PalindromeChecker checker = new PalindromeChecker(); System.out.println("Is palindrome = " + checker.isPalindrome(text)); } /** * This method checks the string for palindrome. We use StringBuilder to * reverse the original string. * * @param text * @return */ private boolean isPalindrome(String text) { System.out.println("Original text = " + text); String reverse = new StringBuilder(text).reverse().toString(); System.out.println("Reverse text = " + reverse); //将原始文本与反向文本进行比较,并忽略其大小写 return text.equalsIgnoreCase(reverse); } }