栈的压入弹出序列
解题思路:
- 使用一个栈,开始为空
- 持续压入pushed数组元素到栈中,直到栈顶元素和popped首元素相同,开始弹出,若弹出后还是匹配,继续弹出
- 最后判断栈是否为空,空则true,否则false
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack();
int j = 0;
for (int elem : pushed) {
stack.push(elem);
while (j < popped.length && !stack.isEmpty() && stack.peek() == popped[j]) {
stack.pop();
j++;
}
}
return j == popped.length;
}