946. 验证栈序列

发布时间 2023-07-04 19:41:46作者: 白露~

1. 题目

读题

 

考查点

 

2. 解法

思路

思路:

遍历pushed数组,

  将元素入栈,然后判断栈顶元素是否与popped数组中的元素相同,

  • 如果相同,就出栈,并移动popped数组的指针,
  • 否则继续入栈。

最后判断栈是否为空,如果为空,返回true,否则返回false。 

 

代码逻辑

具体实现

public boolean validateStackSequences(int[] pushed, int[] popped) {

if (popped == null || popped == null && popped.length != pushed.length) {
return false;
}
Stack<Integer> stack = new Stack<>();
int i = 0;
int n = popped.length;
for (int curr : pushed) {
stack.push(curr);
while (!stack.isEmpty() && i < n && stack.peek() == popped[i]) {
stack.pop();
i++;
}
}
return stack.isEmpty();

}

 

3. 总结