使用堆栈检查给定的字符串是否是回文
伙计们,
我最近接受了采访,并收到了一个关于回文的问题.
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.");
}
}
相关文章