题解 | #栈的压入、弹出序列#
栈的压入、弹出序列
https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106
import java.util.*; public class Solution { public boolean IsPopOrder(int [] pushA, int [] popA) { Stack<Integer> stack = new Stack<>(); int flag = 0; for (int i = 0; i < pushA.length; i++) { //flag < pushA.length用来限制当pushA添加完后只能执行出栈 //栈顶元素不等于popA元素就入栈 //flag用来标记入栈元素在pushA的位置 while (flag < pushA.length && (stack.isEmpty() || stack.peek() != popA[i])) { stack.push(pushA[flag]); flag++; } //栈顶等于popA元素就出栈 if (stack.peek() == popA[i]) { stack.pop(); //不相等说明不可以 } else { return false; } } return true; } }