使用堆栈检查给定的字符串是否是回文

Check if given string is a palindrome using stack(使用堆栈检查给定的字符串是否是回文)

本文介绍了使用堆栈检查给定的字符串是否是回文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,

我最近接受了采访,并收到了一个关于回文的问题.

I was recently interviewed and got a question on Palindrome.

给定一个字符串(可能代表一个日期),检查它是否是一个回文或不使用堆栈.

Given a string ( which might represent a date ), check if it's a palindrome or not using Stack.

我试图想出解决办法,但他不喜欢这样.

I tried to come up with solution, but he didn't like that.

谁能给我看Java的代码片段?

Can anyone show me the code snippet for it in Java ?

谢谢

PS:这不是作业,而是实际的面试问题.

PS : This is not a homework, actual interview question.

推荐答案

import java.util.Stack;

public class PalindromeTest {

    public static void main(String[] args) {

        String input = "test";
        Stack<Character> stack = new Stack<Character>();

        for (int i = 0; i < input.length(); i++) {
            stack.push(input.charAt(i));
        }

        String reverseInput = "";

        while (!stack.isEmpty()) {
            reverseInput += stack.pop();
        }

        if (input.equals(reverseInput))
            System.out.println("Yo! that is a palindrome.");
        else
            System.out.println("No! that isn't a palindrome.");

    }
}

这篇关于使用堆栈检查给定的字符串是否是回文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用堆栈检查给定的字符串是否是回文

基础教程推荐