当前位置:网站首页>Leetcode stack related
Leetcode stack related
2022-07-05 06:13:00 【Dawnlighttt】
List of articles
q20 Valid parenthesis
Answer key
Traversal string , Use stack to save left parenthesis , When the right bracket is encountered , Compare it with the element at the top of the stack .
func isValid(s string) bool {
var stack []byte
for i := 0; i < len(s); i++ {
if s[i] == '(' || s[i] == '[' || s[i] == '{' {
stack = append(stack, s[i])
}
if len(stack) == 0 {
return false
}
if s[i] == ')' {
if stack[len(stack) - 1] == '(' {
stack = stack[:len(stack) - 1]
} else {
return false
}
}
if s[i] == ']' {
if stack[len(stack) - 1] == '[' {
stack = stack[:len(stack) - 1]
} else {
return false
}
}
if s[i] == '}' {
if stack[len(stack) - 1] == '{' {
stack = stack[:len(stack) - 1]
} else {
return false
}
}
}
if len(stack) != 0 {
return false
}
return true
}
q32 Longest valid bracket
Answer key
This problem can be solved by stack , Use the following strategies :
1. The position of brackets in the stack
2. The stack base stores the position of the last redundant right parenthesis , Easy to count , Initially press -1
3. When encountering the closing parenthesis, a value must pop up first , And then determine :
- If the element in the stack is empty after popping , Then update the position of the last redundant right parenthesis
- If it's not empty , Then update the length of the longest valid bracket , The method is to subtract the subscript of the element at the top of the stack from the current subscript
func longestValidParentheses(s string) int {
maxLength := 0
stack := []int{
-1}
for i := 0; i < len(s); i++ {
// If it's left parenthesis , Directly stack the position
if s[i] == '(' {
stack = append(stack, i)
} else {
// Anyway , First pop up an element
stack = stack[:len(stack) - 1]
// What pops up is the stack base element , Then update the subscript of the last redundant right parenthesis
if len(stack) == 0 {
stack = append(stack, i)
// What pops up is not the stack base , Update Max
} else {
if maxLength < i - stack[len(stack) - 1] {
maxLength = i - stack[len(stack) - 1]
}
}
}
}
return maxLength
}
q155 Smallest stack
Answer key
The requirement of this problem is to find the minimum value with constant time complexity , I use an auxiliary stack to solve it .
MinStack There are two stacks in the structure , A main stack , Used to store elements , An auxiliary stack , Used to store minimum value , The top of the auxiliary stack is used to store the current minimum .
Each time the auxiliary stack is pressed, the minimum value between the current main stack and the newly pressed element . So that's a guarantee , If the minimum value of the main stack is at the top of the stack , Behind the bomb stack , The auxiliary stack also pops up accordingly , At this time, the top of the auxiliary stack is still the minimum value of all current elements .
As shown in the figure :
type MinStack struct {
stack []int
minStack []int
}
func Constructor() MinStack {
return MinStack{
stack: make([]int, 0),
minStack: []int{
math.MaxInt32},
}
}
func (this *MinStack) Push(val int) {
this.stack = append(this.stack, val)
if val < this.minStack[len(this.minStack) - 1] {
this.minStack = append(this.minStack, val)
} else {
this.minStack = append(this.minStack, this.minStack[len(this.minStack) - 1])
}
}
func (this *MinStack) Pop() {
this.stack = this.stack[:len(this.stack) - 1]
this.minStack = this.minStack[:len(this.minStack) - 1]
}
func (this *MinStack) Top() int {
return this.stack[len(this.stack) - 1]
}
func (this *MinStack) GetMin() int {
return this.minStack[len(this.minStack) - 1]
}
q224 Basic calculator
Answer key
This problem has only addition and subtraction , Just define a stack .res Used to save the final results ,sign Used to mark the last symbol ,num Used to store numbers .
Then traverse the string , If it is a number, it is stored in num in , If it is + Number or - Add up the previous numbers first :res += num * sign, And then sign Set as 1 perhaps -1, then num Set as 0 that will do . If it's left parenthesis , Then first press the calculation result and the symbol before the bracket onto the stack , And then res Set as 0, Used to save the operation results in brackets . When the right bracket appears , Just compare the result saved in the stack with the calculation result in brackets res Integration .
func calculate(s string) int {
stack, res, num, sign := []int{
}, 0, 0, 1
for i := 0; i < len(stack); i++ {
if s[i] >= '0' && s[i] <= '9' {
num = num * 10 + int(s[i] - '0')
} else if s[i] == '+' {
res += sign * num
num = 0
sign = 1
} else if s[i] == '-' {
res += sign * num
num = 0
sign = -1
} else if s[i] == '(' {
// Push the previous result and symbol onto the stack
stack = append(stack, res)
stack = append(stack, sign)
// Set the result to 0, Just calculate the new result in brackets
res = 0
sign = 1
} else if s[i] == ')' {
res += sign * num
num = 0
res *= stack[len(stack) - 1]
res += stack[len(stack) - 2]
stack = stack[:len(stack) - 2]
}
}
// It ends with either a right parenthesis or a number
if num != 0 {
res += sign * num
}
return res
}
q232 Using stack to realize queue
Answer key
The title provides two stacks , One as a team stack stack1, Press in every time you join the team stack1; One as a team stack stack2, Every time I have to go out of the team , First judge stack2 Is it empty , If it is empty , will stack1 All elements in are pressed stack2 in , Then pop up the top element ; If it's not empty , Just pop up the top element of the stack . Just right, you can implement the queue first in first out feature .
The same is true of the return queue header element .
If two stacks are empty at the same time , Then the queue is empty .
type MyQueue struct {
stack1, stack2 []int
}
func Constructor() MyQueue {
return MyQueue{
}
}
func (this *MyQueue) Push(x int) {
this.stack1 = append(this.stack1, x)
}
func (this *MyQueue) Pop() int {
if len(this.stack2) == 0 {
for len(this.stack1) != 0 {
this.stack2 = append(this.stack2, this.stack1[len(this.stack1) - 1])
this.stack1 = this.stack1[:len(this.stack1) - 1]
}
}
front := this.stack2[len(this.stack2) - 1]
this.stack2 = this.stack2[:len(this.stack2) - 1]
return front
}
func (this *MyQueue) Peek() int {
if len(this.stack2) == 0 {
for len(this.stack1) != 0 {
this.stack2 = append(this.stack2, this.stack1[len(this.stack1) - 1])
this.stack1 = this.stack1[:len(this.stack1) - 1]
}
}
front := this.stack2[len(this.stack2) - 1]
return front
}
func (this *MyQueue) Empty() bool {
if len(this.stack1) == 0 && len(this.stack2) == 0 {
return true
} else {
return false
}
}
q316 Remove duplicate letters
Answer key
First, traverse the string , Record the number of times each letter appears . Then traverse the string again ,exist Array is used to mark whether the current letter already exists in the stack , If there is , Just skip. . If it does not exist, the loop is compared with the letter at the top of the stack , If the letter at the top of the stack is larger than the current letter, and there is also a top of the stack element after it , Pop up the top element of the stack . Finally, put the letters on the stack .
func removeDuplicateLetters(s string) string {
var count [26]int
var exist [26]bool
var stack []rune
for _, v := range s {
count[v - 'a']++
}
for _, v := range s {
if exist[v - 'a'] {
count[v - 'a']--
continue
}
// If the conditions are met, it should be out of the stack
// 1. There are elements in the stack
// 2. The stack top element is larger than the current element
// 3. The stack top element appears later
for len(stack) > 0 && stack[len(stack) - 1] > v && count[stack[len(stack) - 1] - 'a'] > 0 {
exist[stack[len(stack) - 1] - 'a'] = false
stack = stack[:len(stack) - 1]
}
stack = append(stack, v)
count[v - 'a']--
exist[v - 'a'] = true
}
return string(stack)
}
边栏推荐
- The sum of the unique elements of the daily question
- Multi screen computer screenshots will cut off multiple screens, not only the current screen
- Transform optimization problems into decision-making problems
- Quickly use Amazon memorydb and build your own redis memory database
- Simple knapsack, queue and stack with deque
- [practical skills] how to do a good job in technical training?
- Leetcode-6108: decrypt messages
- Dynamic planning solution ideas and summary (30000 words)
- Leetcode-9: palindromes
- [rust notes] 13 iterator (Part 2)
猜你喜欢
![[cloud native] record of feign custom configuration of microservices](/img/39/05cf7673155954c90e75a8a2eecd96.jpg)
[cloud native] record of feign custom configuration of microservices

Spark中groupByKey() 和 reduceByKey() 和combineByKey()

leetcode-6111:螺旋矩阵 IV

Implement an iterative stack

Data visualization chart summary (I)

SQLMAP使用教程(一)

Introduction et expérience de wazuh open source host Security Solution

MatrixDB v4.5.0 重磅发布,全新推出 MARS2 存储引擎!

How to adjust bugs in general projects ----- take you through the whole process by hand

Leetcode-6108: decrypt messages
随机推荐
SPI 详解
Scope of inline symbol
2022 极术通讯-Arm 虚拟硬件加速物联网软件开发
[rust notes] 14 set (Part 2)
The sum of the unique elements of the daily question
【Rust 笔记】16-输入与输出(下)
redis发布订阅命令行实现
Implement an iterative stack
Traditional databases are gradually "difficult to adapt", and cloud native databases stand out
Introduction and experience of wazuh open source host security solution
1.14 - 流水线
[cloud native] record of feign custom configuration of microservices
Data visualization chart summary (I)
Introduction et expérience de wazuh open source host Security Solution
Simple knapsack, queue and stack with deque
[rust notes] 13 iterator (Part 2)
可变电阻器概述——结构、工作和不同应用
Daily question 1342 Number of operations to change the number to 0
927. Trisection simulation
RGB LED infinite mirror controlled by Arduino