您的位置:首页 > 科技 > IT业 > 每日两题 / 20. 有效的括号 155. 最小栈(LeetCode热题100)

每日两题 / 20. 有效的括号 155. 最小栈(LeetCode热题100)

2025/3/18 13:07:52 来源:https://blog.csdn.net/weixin_61432764/article/details/140156116  浏览:    关键词:每日两题 / 20. 有效的括号 155. 最小栈(LeetCode热题100)

20. 有效的括号 - 力扣(LeetCode)
image.png

遇到左括号入栈
遇到右括号判断栈顶是否为匹配的左括号
最后判断栈是否为空

func isValid(s string) bool {var stk []runefor _, value := range s {if value == '(' || value == '{' || value == '[' {stk = append(stk, value)} else if (len(stk) == 0) {return false } else {topchar := stk[len(stk) - 1]stk = stk[:len(stk) - 1]if topchar == '(' && value != ')' {return false } else if topchar == '{' && value != '}' {return false } else if topchar == '[' && value != ']' {return false }}}return len(stk) == 0
}

155. 最小栈 - 力扣(LeetCode)
image.png

要在 O ( 1 ) O(1) O(1)的时间找出最小数,一定需要额外的空间保存信息,这里使用一个辅助栈维护额外的信息
根据栈的先进后出性质,push一个数后,如果该数大于最小数,那么之后获取的最小数一定不是该数,所以无需额外记录该大数的信息。向辅助栈push当前最小数(辅助栈的栈顶)
如果该数小于最小数,那么之后获取的最小数就是该数,需要额外记录该数的信息。向辅助栈push该数
pop操作时,同时pop两个栈的栈顶

type MinStack struct {stk []intmin_stk []int 
}func Constructor() MinStack {return MinStack{stk: []int{},min_stk: []int{},}
}func (this *MinStack) Push(val int)  {this.stk = append(this.stk, val) if len(this.min_stk) == 0 {this.min_stk = append(this.min_stk, val)} else if val > this.min_stk[len(this.min_stk) - 1] {this.min_stk = append(this.min_stk, this.min_stk[len(this.min_stk) - 1])} else {this.min_stk = append(this.min_stk, val)}
}func (this *MinStack) Pop()  {this.stk = this.stk[:len(this.stk) - 1]this.min_stk = this.min_stk[:len(this.min_stk) - 1]
}func (this *MinStack) Top() int {return this.stk[len(this.stk) - 1]
}func (this *MinStack) GetMin() int {return this.min_stk[len(this.min_stk) - 1]
}/*** Your MinStack object will be instantiated and called as such:* obj := Constructor();* obj.Push(val);* obj.Pop();* param_3 := obj.Top();* param_4 := obj.GetMin();*/

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com