Java 栈和队列实现回文判断 - 代码示例
import java.util.*;
public class PalindromeChecker {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = sc.nextLine();
boolean isPalindrome = checkPalindrome(input);
if (isPalindrome) {
System.out.println(input + " is a palindrome.");
} else {
System.out.println(input + " is not a palindrome.");
}
}
public static boolean checkPalindrome(String str) {
Stack<Character> stack = new Stack<>();
Queue<Character> queue = new LinkedList<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
stack.push(c);
queue.add(c);
}
while (!stack.isEmpty() && !queue.isEmpty()) {
if (stack.pop() != queue.remove()) {
return false;
}
}
return true;
}
}
该代码通过栈和队列分别存储字符串中的字符,然后比较两者的顺序是否相同,来判断该字符串是否为回文字符串。如果是,则返回true,否则返回false。
原文地址: https://www.cveoy.top/t/topic/n1KA 著作权归作者所有。请勿转载和采集!