剑指 Offer 31. 栈的压入、弹出序列
直接模拟就好了。
剑指 Offer 31. 栈的压入、弹出序列
class Solution { public boolean validateStackSequences(int[] pushed, int[] popped) { //泛型需要是对象类型所以不能用int Stack<Integer> stack = new Stack<>(); int i = 0; for(int num : pushed){ stack.push(num); //根据代码执行顺序,isEmpty()要写在前面 while(!stack.isEmpty() && popped[i] == stack.peek()){ stack.pop(); i++; } } return stack.isEmpty(); } }