我正在尝试编写一个方法,该方法将整数队列作为参数并检查该队列是否是回文。
我的方法似乎适用于大多数队列,但不适用于其他队列?我无法识别那些它不兼容的特征......
这是我的代码:
public static boolean isPalindrome(Queue<Integer> q) {
boolean result = false;
Stack<Integer> save = new Stack<Integer>();
if(q.isEmpty()){
result = true;
}
for(int i = 0; i < q.size(); i++){
int n = q.remove();
save.push(n);
q.add(n);
}
for(int j = 0; j < q.size(); j++){
int a = q.remove();
int b = save.pop();
if(a == b){
result = true;
}
q.add(a);
}
return result;
}
最佳答案
看起来除了第二个 for 循环之外一切都是正确的。需要更改一下,检查栈和队列的内容是否不同。如果是,则返回false
。并在方法结束时返回true
。
for (int j = 0; j < q.size(); j++) {
int a = q.remove();
int b = save.pop();
if (a != b) {
return false;
}
q.add(a);
}
return true;
关于java - 我的回文检查器对某些不起作用,但对另一些却起作用? (JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22002296/