leetcode 946. 验证栈序列

题解

通过stack模拟入栈出栈

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
func validateStackSequences(pushed []int, popped []int) bool {
n := len(pushed)
if n == 0 {
return true
}
stack := make([]int, 0)
i, j := 0, 0
stack = append(stack, pushed[i])
i++
for {
m := len(stack)
if m > 0 && stack[m-1] == popped[j] {
stack = stack[:m-1]
j++
} else {
if i == n {
break
}
stack = append(stack, pushed[i])
i++
}
}
if len(stack) == 0 {
return true
}
return false
}