模拟题,用栈模拟一遍,最后判断栈是否为空
解题思路
我们遍历出现顺序,如果栈为空或者栈中最后一个元素不等于当前出栈的元素,那么我们就一直进栈,直到找到栈顶的元素等于当前元素,然后让当前元素出栈,我们还需要保证入栈的索引在合理范围内。
class Solution {
public boolean isPopOrder(int [] pushV,int [] popV) {
if(pushV == null && popV == null || pushV.length == 0 && popV.length == 0){
return true;
}
if(pushV.length == 0 || popV.length == 0 || pushV.length != popV.length){
return false;
}
int idx = 0;
int n = pushV.length;
Deque<Integer> stack = new LinkedList<>();
for(int i = 0; i < n; i++){
while(idx < n && (stack.isEmpty()||stack.getLast() != popV[i])){
stack.addLast(pushV[idx++]);
}
if(stack.getLast() == popV[i]){
stack.removeLast();
}
}
return stack.isEmpty();
}
}