20. 有效的括號 - 力扣(LeetCode)
遇到左括號入棧
遇到右括號判斷棧頂是否為匹配的左括號
最后判斷棧是否為空
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)
要在 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();*/