-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatching_brackets.go
55 lines (44 loc) · 1005 Bytes
/
matching_brackets.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
// Package brackets implement a way to validate brackets.
package brackets
// Bracket validates brackets such as [], {}, () to be in the correct order and paired.
func Bracket(input string) bool {
openToClose := map[rune]rune{
'(': ')',
'{': '}',
'[': ']',
}
closeToOpen := map[rune]rune{
']': '[',
')': '(',
'}': '{',
}
var brackets stack
for _, char := range input {
if _, ok := openToClose[char]; ok {
brackets.push(char)
} else if _, ok := closeToOpen[char]; ok {
if len(brackets.items) == 0 {
return false
}
top := brackets.pop()
if top != closeToOpen[char] {
return false
}
}
}
return len(brackets.items) == 0
}
// A collection of items Vertically.
type stack struct {
items []rune
}
// push adds an item to the stack.
func (s *stack) push(r rune) {
s.items = append(s.items, r)
}
// pop returns the top item of the stack.
func (s *stack) pop() rune {
top := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return top
}