我写了一个冗长而复杂的方法,检查队列中的元素列表是否是回文。我知道它可以改进,但我现在的目标是让它通过实践中的所有测试 - 它。我已经超过10分中的9分,但我似乎无法通过的唯一考验是奇数元素/不是回文。
例如: 前面[5,10,-1,4,3,2,2,4,-1,10,5]后面。预期输出应该是假的。我的输出为TRUE。
此外,与其他测试不同,队列中的元素不会显示。与之前提出的与此问题类似的问题不同,我的队列必须恢复到原始状态。到目前为止,这是我的代码:
public static boolean isPalindrome(Queue<Integer> q) {
Stack<Integer> s = new Stack<Integer>();
int size = q.size();
int extra = 0;
if(q.isEmpty())
return true;
else
if (size % 2 == 0) {
for (int i = 0; i < size / 2; i++) {
s.push(q.remove());
}
while (!s.isEmpty()) { // While Stack is not empty:
if (s.peek() != q.peek()) {
int first = s.pop();
s.push(q.remove());
s.push(first);
while (!q.isEmpty())
s.push(q.remove());
while (!s.isEmpty()) {
q.add(s.pop());
}
return false;
}
else {
while (!q.isEmpty())
s.push(q.remove());
while (!s.isEmpty()) {
q.add(s.pop()); // Restore Queue to original order
}
return true;
}
}
for (int k = 0; k < size / 2; k++) {
q.add(q.remove());
s.push(q.remove());
}
for (int l = 0; l < size / 2; l++)
s.push(q.remove());
while (!s.isEmpty())
q.add(s.pop());
}
return true;
}
如果有人在阅读本文时遇到困难,或者可以提出一种方法来减少错综复杂的感觉,我将不胜感激。谢谢,再次抱歉臃肿的代码。
答案 0 :(得分:1)
为什么不使用简单的算法,它不关心它是否会破坏过程中的队列,而是将队列复制为第一步?
public static boolean isPalindrome(Queue<Integer> q) {
return isPalindromeDestructive(copyQueue(q));
}
private static boolean isPalindromeDestructive(Queue<Integer> q) {
//Destructive algorithm that treats q as disposable.
}
private static Queue<Integer> copyQueue(Queue<Integer> q) {
return new LinkedList<Integer>(q);
}
您可以根据需要实施copyQueue,但这样可以。
答案 1 :(得分:0)
Cruncher我按照你的方式复制了队列。我担心奇怪的大小队列,使代码过于复杂。我推荐你的回答,因为这确实有帮助,但没有足够的常旅客里程。
所有真正需要的就是抛弃我第一次发布的笨蛋,这有时候是最好的。
无论如何,这里是。 for循环加载堆栈,使复制Cruncher提到。 while循环只是简单地查看,然后在弹出堆栈时重新加载Queue。更清洁,在问了正确的问题后我花了几分钟。
public static boolean isPalindrome(Queue<Integer> q) {
Stack<Integer> s = new Stack<Integer>();
int size = q.size();
boolean palindrome = true;
for (int i = 0; i < size; i++) {
int value = q.peek();
s.push(value);
q.remove();
q.add(value);
}
while (!s.isEmpty()) {
if (s.peek() != q.peek())
palindrome = false;
s.pop();
q.add(q.remove());
}
return palindrome;
}