Skip to content

Latest commit

 

History

History
24 lines (19 loc) · 584 Bytes

31. 栈的压入、弹出序列.md

File metadata and controls

24 lines (19 loc) · 584 Bytes

解题思路

1. 模拟

用一个栈 q 模拟入栈过程,当 q 栈顶元素与 poped 当前值相等,对 q 进行出栈,且 poped 索引右移,如果最后 q 中无元素,说明 poped 确实是 pushed 的一个出栈序

func validateStackSequences(push []int, pop []int) bool {
    q := make([]int, 0)
    idx := 0
    for _, v := range push {
        q = append(q, v)
        for len(q) != 0 && pop[idx] == q[len(q)-1] {
            q = q[:len(q)-1]
            idx++
        }
    }
    return len(q) == 0
}