题解 | #栈的压入、弹出序列#
栈的压入、弹出序列
https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106?tpId=265&tqId=39233&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D13&difficulty=undefined&judgeStatus=undefined&tags=&title=
模拟入栈的过程:
1如果两个数组都为空返回真值,如果两个数组长度不一致则返回假
首先需要一个辅助栈,然后遍历整个push数组,用两个变量分别标识遍历到两个数组的位置:
1如果当前遍历数组的值与popV的值相同则不入栈
2如果当前遍历数组的值与popV的值不同,则需要判断一下当前的元素是否和栈顶元素相同
3最后将栈中剩余元素和popV中的元素一一对比就可以了
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pushV int整型一维数组 * @param popV int整型一维数组 * @return bool布尔型 */ public boolean IsPopOrder (int[] pushV, int[] popV) { if (pushV.length == 0 && popV.length == 0) return true; if (pushV.length != popV.length) return false; Stack<Integer> stack = new Stack<>(); int i, j; for (i = 0, j = 0; i < pushV.length; i++) { if (pushV[i] != popV[j]) { if (!stack.isEmpty() && stack.peek() == popV[j]) { stack.pop(); j++; i--; } else { stack.push(pushV[i]); } } else { j++; } } while (!stack.isEmpty()) { int temp = stack.pop(); if (temp != popV[j]) return false; j++; } return true; } }