每日两题 / 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();
 */
相关推荐
珊瑚里的鱼6 分钟前
【滑动窗口】LeetCode 1658题解 | 将 x 减到 0 的最小操作数
开发语言·c++·笔记·算法·leetcode·stl
落樱弥城10 分钟前
角点特征:从传统算法到深度学习算法演进
人工智能·深度学习·算法
共享家952732 分钟前
哈希的原理、实现
c++·算法
进击的小白菜42 分钟前
用Java实现单词搜索(LeetCode 79)——回溯算法详解
java·算法·leetcode
珂朵莉MM1 小时前
2024 睿抗机器人开发者大赛CAIP-编程技能赛-专科组(国赛)解题报告 | 珂学家
开发语言·人工智能·算法·leetcode·职场和发展·深度优先·图论
小智学长 | 嵌入式1 小时前
进阶-数据结构部分:2、常用排序算法
java·数据结构·算法
少了一只鹅1 小时前
字符函数和字符串函数
c语言·算法
Dr.9272 小时前
1-10 目录树
java·数据结构·算法
子豪-中国机器人2 小时前
C++ 蓝桥 STEMA 省选拔赛模拟测试题(第一套)
开发语言·c++·算法
callJJ2 小时前
Bellman - Ford 算法与 SPFA 算法求解最短路径问题 ——从零开始的图论讲解(4)
数据结构·算法·蓝桥杯·图论·单源最短路径·bellman- ford算法