Just use a stack to simulate the push and pop process
While stack is empty or peek does not equal to popped current value, push value into stack.
While equal, pop stack and consume popped value.
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> s = new Stack<Integer>();
int i = 0, j = 0;
while (j < popped.length) {
if (s.size() == 0 || s.peek() != popped[j]) {
if (i == pushed.length) return false;
s.push(pushed[i++]);
}
else {
s.pop();
++j;
}
}
return true;
}
}
本文介绍了一种使用栈数据结构来验证两个整数数组是否符合栈的压入和弹出顺序的方法。通过迭代检查,当栈为空或栈顶元素不等于待弹出元素时,将元素压入栈;当两者相等时,进行弹出操作。该方法能够高效地判断给定序列是否有效。

被折叠的 条评论
为什么被折叠?



