[英]My palindrome checker isn't working on some but does on others? (JAVA)
我正在嘗試編寫一種方法,該方法將整數隊列作為參數並檢查該隊列是否為回文式。
我的方法似乎適用於大多數隊列,但不適用於其他隊列? 我無法識別出無法使用的特征...
這是我的代碼:
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;
考慮輸入隊列:[1,1,2]
該方法創建的堆棧save
將為[2,1,1]
在第二個for
循環中,對於j=1
,則a == b == 1
,該方法錯誤地聲明了回文。 通常,如果隊列和堆棧在其各自的索引處具有相同的值,則該方法將失敗。 (例如輸入[4,2,2,5])
存在多個問題,但主要的問題是,一旦該方法要求回文,則斷言是固定的。 如評論中所述,最好假定輸入的不是回文,然后對其進行證明。
在第二個for循環中,您有
if(a == b){
result = true;
}
但是,在循環的其余部分中,它永遠不會再次變為假。 這意味着,在隊列長度為n的情況下,如果第ith個元素和第(ni)個元素相同,則結果為true。 例如,{1、3、5、1}隊列將返回true。
更好的實現方式將使您更直觀地使用筆和紙進行檢查。 您只需要檢查第ith和(ni)個元素,直到找到一個不會成為回文的元素即可。 如果您檢查整個隊列沒有錯誤,那么您就有回文記錄!
這是您可以執行的一種方法:
public static boolean isPalindrome(Queue<Integer> q) {
Stack<Integer> save = new Stack<Integer>();
if(q.isEmpty()){
return 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){
return false; // cannot be a palindrome
}
q.add(a);
}
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.