通过比较堆栈和队列确定回文

时间:2014-03-26 01:58:36

标签: java stack queue palindrome

因此,对于我的任务,我必须编写一个使用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;
    }
}

1 个答案:

答案 0 :(得分:3)

您将字符串添加到队列和堆栈中,通常应避免对字符串使用标准的相等性检查(因为它们会比较对象标识而不是内容)。

变化:

if (queue.dequeue( ) != stack.pop( ))

为:

if (!queue.dequeue().equals(stack.pop()))

例如,此代码(稍微修改)可以正常工作:

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;
    }
}

输出:

a
b
c
b
a
true
a
b
c
d
e
false