每日两题 / 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();
 */
相关推荐
sin_hielo6 分钟前
leetcode 3047
数据结构·算法·leetcode
JAI科研7 分钟前
MICCAI 2025 IUGC 图像超声关键点检测及超声参数测量挑战赛
人工智能·深度学习·算法·计算机视觉·自然语言处理·视觉检测·transformer
mit6.8248 分钟前
思维|状压dp
算法
天赐学c语言9 分钟前
1.17 - 排序链表 && 虚函数指针是什么时候初始化的
数据结构·c++·算法·链表·leecode
wu_asia14 分钟前
C语言实现子串出现次数统计
算法
一条大祥脚18 分钟前
一题N解 两种分块|四维莫队|容斥+二维莫队|希尔伯特排序莫队|zorder排序莫队
数据结构·c++·算法
Remember_99320 分钟前
【数据结构】二叉树:从基础到应用全面解析
java·数据结构·b树·算法·leetcode·链表
2501_9403152621 分钟前
蓝桥云课:分巧克力(二分查找法)
数据结构·c++·算法
csuzhucong21 分钟前
2种闪蝶魔方(待更新)
算法
VT.馒头22 分钟前
【力扣】2637. 有时间限制的 Promise 对象
前端·javascript·leetcode·typescript