Problem: 946. 验证栈序列
入栈数组入栈,遇到弹出栈相同元素时弹出,最后判断栈是否为空。特判条件记得特判
Code
Java
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
if(pushed.length==0&&pushed.length==popped.length)return true;
if(pushed.length!=popped.length)return false;
Stack<Integer>stack=new Stack<>();
for(int i=0,j=0;i<popped.length;i++)
{
while((stack.isEmpty()||popped[i]!=stack.peek())&&j<popped.length)
{
stack.push(pushed[j]);
j++;
}
if(stack.peek()==popped[i])stack.pop();
}
if(!stack.isEmpty())return false;
else return true;
}
}