Skip to content

Commit bbab88a

Browse files
committed
add LeetCode 946. 验证栈序列
1 parent 63e60c6 commit bbab88a

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
给定 `pushed``popped` 两个序列,每个序列中的 值都不重复,只有当它们可能是在最初空栈上进行的推入 `push` 和弹出 `pop` 操作序列的结果时,返回 `true`;否则,返回 `false`
6+
7+
8+
9+
示例 1:
10+
11+
```javascript
12+
输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
13+
输出:true
14+
解释:我们可以按以下顺序执行:
15+
push(1), push(2), push(3), push(4), pop() -> 4,
16+
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
17+
```
18+
19+
示例 2:
20+
21+
```javascript
22+
输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
23+
输出:false
24+
解释:1 不能在 2 之前弹出。
25+
```
26+
27+
28+
提示:
29+
30+
```javascript
31+
0 <= pushed.length == popped.length <= 1000
32+
0 <= pushed[i], popped[i] < 1000
33+
pushed 是 popped 的排列。
34+
```
35+
36+
来源:力扣(LeetCode)
37+
链接:https://leetcode-cn.com/problems/validate-stack-sequences
38+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
39+
40+
41+
## 解题思路
42+
借助一个新栈来存放入栈的元素,然后每次和出栈的元素进行比对,如果匹配成功,双方进行出栈操作,最后,如果这个新栈为空,那么代表这个栈入栈和出栈序列是合理的,返回 `true`,否则返回`false`
43+
44+
```javascript
45+
/**
46+
* @param {number[]} pushed
47+
* @param {number[]} popped
48+
* @return {boolean}
49+
*/
50+
var validateStackSequences = function(pushed, popped) {
51+
// 借助一个新的栈
52+
let stack = []
53+
for(let cur of pushed){
54+
// 存放入栈的元素
55+
stack.push(cur)
56+
// 和出栈元素进行比对,如果匹配都弹出栈
57+
while(stack[stack.length-1] === popped[0] && stack.length){
58+
stack.pop()
59+
popped.shift()
60+
}
61+
}
62+
return !stack.length
63+
};
64+
```
65+
66+
## 最后
67+
文章产出不易,还望各位小伙伴们支持一波!
68+
69+
往期精选:
70+
71+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
72+
73+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
74+
75+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
76+
77+
```javascript
78+
学如逆水行舟,不进则退
79+
```

0 commit comments

Comments
 (0)