-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.go
112 lines (88 loc) · 1.81 KB
/
stack.go
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package algo
import (
"sync"
)
// Stack uses an array as the underlying data structure.
type Stack[T any] struct {
mu sync.RWMutex
data []T
}
func NewStack[T any]() *Stack[T] {
return &Stack[T]{
mu: sync.RWMutex{},
data: []T{},
}
}
func (s *Stack[T]) Push(v T) {
s.mu.Lock()
defer s.mu.Unlock()
s.data = append(s.data, v)
}
func (s *Stack[T]) Pop() T {
s.mu.Lock()
defer s.mu.Unlock()
if s.isEmpty() {
return s.nilType()
}
v := s.data[len(s.data)-1]
s.data = s.data[:len(s.data)-1]
return v
}
func (s *Stack[T]) Peak() T {
s.mu.RLock()
defer s.mu.RUnlock()
if s.isEmpty() {
return s.nilType()
}
return s.data[len(s.data)-1]
}
func (s *Stack[T]) Size() int {
s.mu.RLock()
defer s.mu.RUnlock()
return len(s.data)
}
func (s *Stack[T]) isEmpty() bool {
// no locking, as this is internal and should be done by caller.
return len(s.data) == 0
}
func (s *Stack[T]) nilType() T {
var t T
return t
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Usecase: linter
type Linter struct {
stack *Stack[any]
}
func newLinter() *Linter {
return &Linter{stack: NewStack[any]()}
}
func (l *Linter) lint(text string) bool {
brace := map[rune]rune{
'}': '{',
']': '[',
')': '(',
}
// Loop through each char.
for _, char := range text {
switch char {
case '(', '[', '{':
l.stack.Push(char)
case ')', ']', '}':
poppedOpenBrace := l.stack.Pop()
// If the stack was empty.
if poppedOpenBrace == nil {
return false
}
// If the popped brace doesn't correspond to the closing brace.
if check := brace[char]; check != poppedOpenBrace {
return false
}
}
}
// There are remaining chars in the stack, it lacks a closing brace.
if l.stack.Peak() != nil {
return false
}
return true
}