每日两题 / 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();
 */
相关推荐
司铭鸿1 天前
化学式解析的算法之美:从原子计数到栈的巧妙运用
linux·运维·服务器·算法·动态规划·代理模式·哈希算法
2501_941143731 天前
缓存中间件Redis与Memcached在高并发互联网系统优化与实践经验分享
leetcode
ekprada1 天前
DAY 18 推断聚类后簇的类型
算法·机器学习·支持向量机
生信大表哥1 天前
Python单细胞分析-基于leiden算法的降维聚类
linux·python·算法·生信·数信院生信服务器·生信云服务器
玫瑰花店1 天前
万字C++中锁机制和内存序详解
开发语言·c++·算法
Elias不吃糖1 天前
LeetCode每日一练(209, 167)
数据结构·c++·算法·leetcode
铁手飞鹰1 天前
单链表(C语言,手撕)
数据结构·c++·算法·c·单链表
悦悦子a啊1 天前
项目案例作业(选做):使用文件改造已有信息系统
java·开发语言·算法
小殊小殊1 天前
【论文笔记】知识蒸馏的全面综述
人工智能·算法·机器学习
无限进步_1 天前
C语言动态内存管理:掌握malloc、calloc、realloc和free的实战应用
c语言·开发语言·c++·git·算法·github·visual studio