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

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

遇到左括号入栈

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

最后判断栈是否为空

go 复制代码
func isValid(s string) bool {
    var stk []rune
    for _, 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)

要在 O ( 1 ) O(1) O(1)的时间找出最小数,一定需要额外的空间保存信息,这里使用一个辅助栈维护额外的信息

根据栈的先进后出性质,push一个数后,如果该数大于最小数,那么之后获取的最小数一定不是该数,所以无需额外记录该大数的信息。向辅助栈push当前最小数(辅助栈的栈顶)

如果该数小于最小数,那么之后获取的最小数就是该数,需要额外记录该数的信息。向辅助栈push该数

pop操作时,同时pop两个栈的栈顶

go 复制代码
type MinStack struct {
    stk []int
    min_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();
 */
相关推荐
iAkuya6 分钟前
(leetcode)力扣100 57电话号码的字母组合(回溯)
算法·leetcode·深度优先
m0_7369191019 分钟前
模板元编程性能分析
开发语言·c++·算法
win x20 分钟前
JavaSE(基础)高频面试点及 知识点
java·面试·职场和发展
pen-ai26 分钟前
【YOLO系列】 YOLOv1 目标检测算法原理详解
算法·yolo·目标检测
2301_765703141 小时前
C++中的职责链模式实战
开发语言·c++·算法
StandbyTime1 小时前
《算法笔记》学习记录-第一章
c++·算法·算法笔记
近津薪荼1 小时前
优选算法——双指针8(单调性)
数据结构·c++·学习·算法
格林威1 小时前
Baumer相机铆钉安装状态检测:判断铆接是否到位的 5 个核心算法,附 OpenCV+Halcon 的实战代码!
人工智能·opencv·算法·计算机视觉·视觉检测·工业相机·堡盟相机
星空露珠2 小时前
速算24点检测生成核心lua
开发语言·数据库·算法·游戏·lua
happygrilclh2 小时前
高压高频电源的pid算法
算法