剑指 Offer 31. 栈的压入、弹出序列
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。
示例 1:
输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
输出:true
解释:我们可以按以下顺序执行:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
示例 2:
输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
输出:false
解释:1 不能在 2 之前弹出。
来源:力扣(LeetCode)
链接:点击跳转https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof
思路:
模拟出栈和入栈的操作
- 循环出栈数组
- 找到第一个出栈数组的元素,然后遍历入栈数组,找到与之对应的元素下标,然后把下标之前没入过栈的元素都入栈。
- 判断栈顶元素是否和出栈数组的下标元素相等,若不相等返回false
- 若退出出栈数组的循环,则符合要求,返回true
class Solution {
public static boolean validateStackSequences(int[] pushed, int[] popped) {
int push = pushed.length;
int pop = popped.length;
int i = 0; //入栈下标
int j = 0; //出栈下标
Stack<Integer> stack = new Stack<>();
//下标范围内循环
while(j < pop) {
int start = i; //记录入栈的下标
//若栈为空 或 栈顶元素不等于弹出j下标元素
//则进行入栈模拟,找到下个出栈的元素,然后入从start到k
if(stack.isEmpty() || stack.peek() != popped[j]) {
for(int k = i; k < push; k++) {
//先找到出栈元素 对应的 入栈元素的下标,为k
if(pushed[i] == popped[j]) {
//从start到k元素入栈
for(int n = start; n <= k; n++) {
stack.push(pushed[n]);
}
i++;
break; //入完栈循环结束
}
i++;
}
}
//判断栈顶元素和出栈元素是否相等,相等遍历下一个,不等就返回false
if(stack.pop() == popped[j]) {
j++;
}else {
return false;
}
}
//如果程序走到这,证明出栈元素遍历完成,符合入栈出栈条件,返回true
return true;
}
}
大佬算法流程:
- 初始化: 辅助栈 stack ,弹出序列的索引 i ;
- 遍历压栈序列: 各元素记为 num ;
(1)元素 num 入栈;
(2)循环出栈:若stack 的栈顶元素 == 弹出序列元素 popped[i] ,则执行出栈与 i++ - 返回值: 若 stack 为空,则此弹出序列合法。
作者:jyd
链接:https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof/solution/mian-shi-ti-31-
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack<>();
int i = 0;
for(int num : pushed) {
stack.push(num); // num 入栈
while(!stack.isEmpty() && stack.peek() == popped[i]) { // 循环判断与出栈
stack.pop();
i++;
}
}
return stack.isEmpty();
}
}