题解 | #栈的压入、弹出序列#
栈的压入、弹出序列
https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pushV int整型一维数组 * @param popV int整型一维数组 * @return bool布尔型 */ public boolean IsPopOrder (int[] pushV, int[] popV) { Stack<Integer> stack = new Stack<>(); int n = pushV.length; int j = 0; for (int i = 0; i < n ; i++) { stack.push(pushV[i]); while(!stack.isEmpty() && stack.peek().equals(popV[j])){ stack.pop(); j++; } } return stack.isEmpty(); } }
思路:
- 使用辅助栈,作为模拟入栈
- 确定入栈以及出栈。
- 入栈:遍历入栈数组,遍历一次入栈一次。
- 出栈:用辅助栈顶元素和出栈数组进行判断,相同的话则出栈,出栈数组下标前进
- 返回结果:辅助栈为空则说明出栈数组成立,直接return stack.isEmpty();