the leetcode link

剑指 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 之前弹出。

提示:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed 是 popped 的排列。

解题思路

既然本题需要模栈的压入、弹出序列,就要模拟到底,自己设计一个简单的栈

  1. 设计栈:定义一个长度为pushed.length数组作为栈,定义一个整型变量作为栈顶
  2. 枚举压栈,当栈顶元素和出栈的第一个元素相同,则弹栈,出栈列表指针后移并继续判断。
  3. 最后判断出栈列表指针是否指向出栈列表的末尾。

    代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
    int[] stack = new int[pushed.length];
    int top = 0, j = 0;
    for(int i = 0; i < pushed.length; i++){
    stack[top] = pushed[i]; // push

    while(j < popped.length && top >= 0 && stack[top] == popped[j]){
    top--; // pop
    j++;
    }

    top++;
    }

    return j==popped.length;
    }
    }

空间优化:把已经枚举过的pushed[]前部分作为栈

空间优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
int top = 0, j = 0;
for(int i = 0; i < pushed.length; i++){
pushed[top] = pushed[i]; // push

while(j < popped.length && top >= 0 && pushed[top] == popped[j]){
top--; // pop
j++;

}

top++;
}

return j==popped.length;
}
}