题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。(注意:这两个序列的长度是相等的)
示例1
输入
[1,2,3,4,5],[4,3,5,1,2]
返回值
false
核心代码实现
import java.util.*;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if(pushA.length == 0 || popA.length == 0 || pushA.length != popA.length){
return false;
}
Stack<Integer> stack = new Stack<>();
int index = 0;
for(int i = 0; i < pushA.length; i++){
//将pushA中的元素依次压入栈
stack.push(pushA[i]);
//栈非空时比较栈的最后一位与popA的第一位是否相同,若相等则弹出该元素,继续比较下一对
while(!stack.isEmpty() && stack.peek() == popA[index]){
stack.pop();
index++;
}
}
//若stack为空,则说明popA为pushA的弹出顺序
return stack.isEmpty();
}
}