输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof
public static boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack<>();
int index = 0;
for (int i = 0; i < pushed.length; i++){
//将第i个元素压入堆栈
stack.push(pushed[i]);
//看当前的栈顶元素是不是待pop出的元素,是就pop出来,不是就继续push
while(stack.size() != 0 && stack.peek() == popped[index]){
stack.pop();
index ++;
}
}
//如果poped数组的弹出顺序合法,则最后堆栈为空
return stack.isEmpty();
}