【发布时间】:2021-03-28 07:09:41
【问题描述】:
在一副纸牌中,每张纸牌上都写有一个整数。
当且仅当可以将整个牌组分成 1 组或多组卡片时才返回 true,其中:
每组至少有 2 张卡片。 每组中的所有卡片都具有相同的整数。
示例:
输入:deck = [1,2,3,4,4,3,2,1]
输出:真
说明:可能的分区[1,1],[2,2],[3,3],[4,4]。
我尝试使用堆栈解决此问题,但它没有按预期工作,并且在应该打印为 true 的地方打印 false。为了清楚我的代码,我添加了注释。
打包练习pkg;
import java.util.Stack;
public class DeckInteger {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
//declaring individual variable for each integer and setting all of them to zero
int p_1=0,p_2=0,p_3=0,p_4=0,p_5=0,p_6=0,p_7=0,p_8=0,p_9=0;
//adding element which can form pair and should return true
stack.add(1);
stack.add(2);
stack.add(1);
stack.add(2);
stack.add(1);
stack.add(2);
//checking till stack is empty and comparing the top of stack to all the individual integer and incrementing them and popping the top element
while(stack.empty()==false) {
if(stack.peek()==1) {
p_1+=1;
stack.pop();
break;
} else if(stack.peek()==2) {
p_2+=1;
stack.pop();
break;
} else if(stack.peek()==3) {
stack.pop();
p_3+=1;
break;
} else if(stack.peek()==4) {
stack.pop();
p_4+=1;
break;
} else if(stack.peek()==5) {
stack.pop();
p_5+=1;
break;
} else if(stack.peek()==6) {
stack.pop();
p_6+=1;
break;
} else if(stack.peek()==7) {
stack.pop();
p_7+=1;
break;
} else if(stack.peek()==8) {
stack.pop();
p_8+=1;
break;
} else {
stack.pop();
p_9+=1;
break;
}
}
//checking if any of the integer variable have the value 1 then it cannot form pair as x>=2 so it should print false
if(p_1==1||p_2==1||p_3==1||p_4==1||p_5==1||p_6==1||p_7==1||p_8==1||p_9==1) {
System.out.println("False");
}
//print true as if any of the variable have a value other than one
else {
System.out.println("True");
}
}
}
【问题讨论】:
标签: java algorithm debugging stack logic