lotus

贵有恒何必三更眠五更起 最无益只怕一日曝十日寒

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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. 总结

posted on 2023-07-04 19:34  白露~  阅读(10)  评论(0编辑  收藏  举报