|
| 1 | +# [面试题31. 栈的压入、弹出序列](https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof/) |
| 2 | + |
| 3 | +## 题目描述 |
| 4 | +<!-- 这里写题目描述 --> |
| 5 | +输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。 |
| 6 | + |
| 7 | +**示例 1:** |
| 8 | + |
| 9 | +``` |
| 10 | +输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1] |
| 11 | +输出:true |
| 12 | +解释:我们可以按以下顺序执行: |
| 13 | +push(1), push(2), push(3), push(4), pop() -> 4, |
| 14 | +push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 |
| 15 | +``` |
| 16 | + |
| 17 | +**示例 2:** |
| 18 | + |
| 19 | +``` |
| 20 | +输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2] |
| 21 | +输出:false |
| 22 | +解释:1 不能在 2 之前弹出。 |
| 23 | +``` |
| 24 | + |
| 25 | +**提示:** |
| 26 | + |
| 27 | +1. `0 <= pushed.length == popped.length <= 1000` |
| 28 | +2. `0 <= pushed[i], popped[i] < 1000` |
| 29 | +3. `pushed` 是 `popped` 的排列。 |
| 30 | + |
| 31 | +## 解法 |
| 32 | +<!-- 这里可写通用的实现逻辑 --> |
| 33 | +借助一个辅助栈实现。 |
| 34 | + |
| 35 | +### Python3 |
| 36 | +<!-- 这里可写当前语言的特殊实现逻辑 --> |
| 37 | + |
| 38 | +```python |
| 39 | +class Solution: |
| 40 | + def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: |
| 41 | + t = [] |
| 42 | + for num in popped: |
| 43 | + while len(t) == 0 or t[-1] != num: |
| 44 | + if len(pushed) == 0: |
| 45 | + return False |
| 46 | + t.append(pushed[0]) |
| 47 | + pushed = pushed[1:] |
| 48 | + t.pop() |
| 49 | + return True |
| 50 | + |
| 51 | +``` |
| 52 | + |
| 53 | +### Java |
| 54 | +<!-- 这里可写当前语言的特殊实现逻辑 --> |
| 55 | + |
| 56 | +```java |
| 57 | +class Solution { |
| 58 | + public boolean validateStackSequences(int[] pushed, int[] popped) { |
| 59 | + Stack<Integer> t = new Stack<>(); |
| 60 | + int i = 0, n = pushed.length; |
| 61 | + for (int num : popped) { |
| 62 | + while (t.empty() || t.peek() != num) { |
| 63 | + if (i == n) { |
| 64 | + return false; |
| 65 | + } |
| 66 | + t.push(pushed[i++]); |
| 67 | + } |
| 68 | + t.pop(); |
| 69 | + } |
| 70 | + return true; |
| 71 | + } |
| 72 | +} |
| 73 | +``` |
| 74 | + |
| 75 | +### ... |
| 76 | +``` |
| 77 | +
|
| 78 | +``` |
0 commit comments