使用堆栈检查给定的字符串是否为回文结构 [英] Check if given string is a palindrome using stack
本文介绍了使用堆栈检查给定的字符串是否为回文结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
伙计,
我最近接受了采访,并在Palindrome上得到了一个问题。
I was recently interviewed and got a question on Palindrome.
给定一个字符串(可能代表一个日期),检查它是否为
palindrome或不使用Stack。
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.");
}
}
这篇关于使用堆栈检查给定的字符串是否为回文结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文