-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution.go
47 lines (41 loc) · 907 Bytes
/
solution.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
package main
import "fmt"
type stack []byte
func (s stack) Push(v byte) stack {
return append(s, v)
}
func (s stack) Pop() (stack, byte) {
return s[:len(s)-1], s[len(s)-1]
}
func isValid(str string) bool {
// create the stack to keep track of brackets
var s stack
//s := make(stack, 0)
// create a hash map to keep track of mappings
m := map[byte]byte{')': '(', '}': '{', ']': '['}
// for every brackets in the expressions
for i := range str {
// if the character is an closing bracket
if _, ok := m[str[i]]; ok {
// get the top byte in the stack
var topByte byte
if len(s) != 0 {
s, topByte = s.Pop()
} else {
// placeholder
topByte = '#'
}
// if the closing bracket is not our top byte
if m[str[i]] != topByte {
return false
}
} else {
s = s.Push(str[i])
}
}
return len(s) == 0
}
func main() {
str := "{}["
fmt.Println(isValid(str))
}