代码随想录算法训练营第十天 | 232、225、20、1047

232. 用栈实现队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package main

type MyQueue struct {
inStack []int
outStack []int
}

func Constructor() MyQueue {
return MyQueue{
inStack: make([]int, 0),
outStack: make([]int, 0),
}
}

func (this *MyQueue) Push(x int) {
this.inStack = append(this.inStack, x)
}

func (this *MyQueue) Pop() int {
if len(this.outStack) == 0 {
for len(this.inStack) > 0 {
val := this.inStack[len(this.inStack)-1]
this.inStack = this.inStack[:len(this.inStack)-1]
this.outStack = append(this.outStack, val)
}
}
res := this.outStack[len(this.outStack)-1]
this.outStack = this.outStack[:len(this.outStack)-1]
return res
}

func (this *MyQueue) Peek() int {
if len(this.outStack) == 0 {
for len(this.inStack) > 0 {
val := this.inStack[len(this.inStack)-1]
this.inStack = this.inStack[:len(this.inStack)-1]
this.outStack = append(this.outStack, val)
}
}
return this.outStack[len(this.outStack)-1]
}

func (this *MyQueue) Empty() bool {
return len(this.inStack) == 0 && len(this.outStack) == 0
}

225. 用队列实现栈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package main

type MyStack struct {
queue []int
}

func Constructor() MyStack {
return MyStack{
queue: make([]int, 0),
}
}

func (this *MyStack) Push(x int) {
// 先将元素加入队列尾部
this.queue = append(this.queue, x)
// 将前 n-1 个元素依次出队并重新入队,使得新元素位于队列前端
size := len(this.queue)
for i := 0; i < size-1; i++ {
val := this.queue[0]
this.queue = this.queue[1:]
this.queue = append(this.queue, val)
}
}

func (this *MyStack) Pop() int {
val := this.queue[0]
this.queue = this.queue[1:]
return val
}

func (this *MyStack) Top() int {
return this.queue[0]
}

func (this *MyStack) Empty() bool {
return len(this.queue) == 0
}

20. 有效的括号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main

func isValid(s string) bool {
stack := []rune{}
mapping := map[rune]rune{
')': '(',
'}': '{',
']': '[',
}

for _, char := range s {
if char == '(' || char == '{' || char == '[' {
stack = append(stack, char)
} else {
if len(stack) == 0 {
return false
}
top := stack[len(stack)-1]
if mapping[char] != top {
return false
}
stack = stack[:len(stack)-1]
}
}
return len(stack) == 0
}

1047. 删除字符串中的所有相邻重复项

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

func removeDuplicates(s string) string {
stack := []byte{}
for i := 0; i < len(s); i++ {
if len(stack) > 0 && stack[len(stack)-1] == s[i] {
stack = stack[:len(stack)-1]
} else {
stack = append(stack, s[i])
}
}
return string(stack)
}