用java的栈实现判断输入字符串是否为回文字符串
下面是用Java栈实现判断输入字符串是否为回文字符串的示例代码:
import java.util.*;
public class Palindrome {
    public static boolean isPalindrome(String str) {
        Stack<Character> stack = new Stack<>();
        int len = str.length();
        int mid = len / 2;
        for (int i = 0; i < mid; i++) {
            stack.push(str.charAt(i));
        }
        if (len % 2 != 0) {
            mid++;
        }
        for (int i = mid; i < len; i++) {
            if (stack.pop() != str.charAt(i)) {
                return false;
            }
        }
        return true;
    }
    public static void main(String[] args) {
        String str1 = "racecar";
        String str2 = "hello";
        System.out.println(str1 + " is palindrome? " + isPalindrome(str1));
        System.out.println(str2 + " is palindrome? " + isPalindrome(str2));
    }
}
该代码中,首先创建了一个栈对象来存储输入字符串的前半部分字符。然后,遍历输入字符串的后半部分字符,同时从栈中弹出字符进行比较。如果有任何一个字符不相等,就说明该字符串不是回文字符串,返回false。如果遍历完成后都没有返回false,则说明该字符串是回文字符串,返回true。
在示例代码中,测试了两个字符串:一个是回文字符串"racecar",另一个不是回文字符串"hello"。运行结果如下:
racecar is palindrome? true
hello is palindrome? false
``
原文地址: https://www.cveoy.top/t/topic/e29b 著作权归作者所有。请勿转载和采集!