AcWing打卡活动
《剑指Offer》打卡活动
周三第八题 栈的压入、弹出序列
/**
* 思路
* 使用一个栈(stackV)依次压入pushV数组的值
* 使用一个变量j记录弹出顺序
* 在压入的过程中,如果该栈(stackV)的第一个元素等于popV[j],则弹出来(碰到之后必须弹出,不然后面将会没有机会弹出)
* 计数器加一
* 如果popV中的元素弹完,则表示符合
*
*
*/
class Solution {
public boolean isPopOrder(int [] pushV,int [] popV) {
// 参数校验
if(pushV.length <= 0 || popV.length <= 0 || pushV.length != popV.length) {
return pushV.length <= 0 && popV.length <= 0;
}
Stack<Integer> stackV = new Stack();
int j = 0; // popV计数器
for(int i = 0; i < pushV.length; i++) {
stackV.push(pushV[i]);
// 如果值相等则准备弹出
while(!stackV.empty() && stackV.peek() == popV[j]) {
j++;
stackV.pop();
// popV中的元素弹完,符合弹出序列
if(j == popV.length) {
return true;
}
}
}
return false;
}
}