Skip to content

Commit 3dfde88

Browse files
committed
feat: add python and java solutions to lcof question
添加《剑指 Offer》题解:面试题31. 栈的压入、弹出序列
1 parent 4cd13d9 commit 3dfde88

File tree

3 files changed

+106
-0
lines changed

3 files changed

+106
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
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+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
public boolean validateStackSequences(int[] pushed, int[] popped) {
3+
Stack<Integer> t = new Stack<>();
4+
int i = 0, n = pushed.length;
5+
for (int num : popped) {
6+
while (t.empty() || t.peek() != num) {
7+
if (i == n) {
8+
return false;
9+
}
10+
t.push(pushed[i++]);
11+
}
12+
t.pop();
13+
}
14+
return true;
15+
}
16+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
class Solution:
2+
def validateStackSequences(self, pushed: List[int],
3+
popped: List[int]) -> bool:
4+
t = []
5+
for num in popped:
6+
while len(t) == 0 or t[-1] != num:
7+
if len(pushed) == 0:
8+
return False
9+
t.append(pushed[0])
10+
pushed = pushed[1:]
11+
t.pop()
12+
return True

0 commit comments

Comments
 (0)