Java 通过比较堆栈和队列确定回文
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22650069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Determine Palindrome by Comparing Stack and Queue
提问by Joey Platt
So for my assignment I have to write a program that uses instances of StackArrayBased.java and QueueArrayBased.java and sends a string to both of them and compares the dequeue() and pop() method returns to determine if the string is a palindrome. I have written the program but it is not returning the correct boolean, please help.
因此,对于我的作业,我必须编写一个程序,该程序使用 StackArrayBased.java 和 QueueArrayBased.java 的实例并向它们发送一个字符串,并比较 dequeue() 和 pop() 方法的返回值以确定该字符串是否为回文。我已经编写了程序,但它没有返回正确的布尔值,请帮忙。
public class IsPalindrome{
public static void main(String[]args){
String str = new String("abcba");
String str2 = new String("abcde");
System.out.println(isPal(str));
System.out.println(isPal(str2));
}
public static boolean isPal(String str)
{
StackArrayBased stack = new StackArrayBased();
QueueArrayBased queue = new QueueArrayBased();
String s = new String();
for (int i = 0; i < str.length( ); i++) {
s = "" + str.charAt(i);
System.out.println(s);
queue.enqueue(s);
stack.push(s);
}
// start to compare
while (!queue.isEmpty( )) {
if (queue.dequeue( ) != stack.pop( ))
return false;
}
// finished w/ empty queue (and empty stack)
return true;
}
}
采纳答案by paxdiablo
You're adding stringsto the queue and stack and you should generally avoid using the standard equality checks for strings (since they compare object identity rather than content).
您将字符串添加到队列和堆栈中,并且通常应该避免对字符串使用标准的相等性检查(因为它们比较的是对象标识而不是内容)。
Change:
改变:
if (queue.dequeue( ) != stack.pop( ))
to:
到:
if (!queue.dequeue().equals(stack.pop()))
For example, this code (modified somewhat) works correctly:
例如,此代码(稍作修改)可以正常工作:
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class Test {
public static void main(String[]args){
String str = new String("abcba");
String str2 = new String("abcde");
System.out.println(isPal(str));
System.out.println(isPal(str2));
}
public static boolean isPal(String str)
{
Stack<String> stack = new Stack<String>();
Queue<String> queue = new LinkedList<String>();
String s = new String();
for (int i = 0; i < str.length( ); i++) {
s = "" + str.charAt(i);
System.out.println(s);
queue.add(s);
stack.push(s);
}
// start to compare
while (!queue.isEmpty( )) {
if (!queue.remove().equals(stack.pop( )))
return false;
}
// finished w/ empty queue (and empty stack)
return true;
}
}
outputting:
输出:
a
b
c
b
a
true
a
b
c
d
e
false