企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# java 程序:使用`Stack`,`Queue`,`for`或`while`循环检查回文串 > 原文: [https://beginnersbook.com/2014/01/java-program-to-check-palindrome-string/](https://beginnersbook.com/2014/01/java-program-to-check-palindrome-string/) 在本教程中,我们将看到**程序来检查给定的`String`是否是回文**。以下是实现目标的方法。 1)使用堆栈 2)使用队列 3)使用`for`/`while`循环 **程序 1:使用堆栈**进行回文检查 ```java import java.util.Stack; import java.util.Scanner; class PalindromeTest { public static void main(String[] args) { System.out.print("Enter any string:"); Scanner in=new Scanner(System.in); String inputString = in.nextLine(); Stack stack = new Stack(); for (int i = 0; i < inputString.length(); i++) { stack.push(inputString.charAt(i)); } String reverseString = ""; while (!stack.isEmpty()) { reverseString = reverseString+stack.pop(); } if (inputString.equals(reverseString)) System.out.println("The input String is a palindrome."); else System.out.println("The input String is not a palindrome."); } } ``` 输出 1: ```java Enter any string:abccba The input String is a palindrome. ``` 输出 2: ```java Enter any string:abcdef The input String is not a palindrome. ``` **程序 2:回顾检查使用队列** ```java import java.util.Queue; import java.util.Scanner; import java.util.LinkedList; class PalindromeTest { public static void main(String[] args) { System.out.print("Enter any string:"); Scanner in=new Scanner(System.in); String inputString = in.nextLine(); Queue queue = new LinkedList(); for (int i = inputString.length()-1; i >=0; i--) { queue.add(inputString.charAt(i)); } String reverseString = ""; while (!queue.isEmpty()) { reverseString = reverseString+queue.remove(); } if (inputString.equals(reverseString)) System.out.println("The input String is a palindrome."); else System.out.println("The input String is not a palindrome."); } } ``` 输出 1: ```java Enter any string:xyzzyx xyzzyx The input String is a palindrome. ``` 输出 2: ```java Enter any string:xyz The input String is not a palindrome. ``` **程序 3:使用`for`循环/`While`循环和字符串函数`charAt`** ```java import java.util.Scanner; class PalindromeTest { public static void main(String args[]) { String reverseString=""; Scanner scanner = new Scanner(System.in); System.out.println("Enter a string to check if it is a palindrome:"); String inputString = scanner.nextLine(); int length = inputString.length(); for ( int i = length - 1 ; i >= 0 ; i-- ) reverseString = reverseString + inputString.charAt(i); if (inputString.equals(reverseString)) System.out.println("Input string is a palindrome."); else System.out.println("Input string is not a palindrome."); } } ``` 输出 1: ```java Enter a string to check if it is a palindrome: aabbaa Input string is a palindrome. ``` 输出 2: ```java Enter a string to check if it is a palindrome: aaabbb Input string is not a palindrome. ``` 如果你想在上面的程序中使用`While`循环,那么用这段代码替换`for`循环: ```java int i = length-1; while ( i >= 0){ reverseString = reverseString + inputString.charAt(i); i--; } ```