-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalid_parentheses.go
57 lines (54 loc) · 1.16 KB
/
valid_parentheses.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
// Package valid_parentheses
//
// Given a string `s` containing just the characters in brackets, determine if the input string is valid.
//
// An input string is valid if:
//
// - Open `brackets` must be closed by the same type of `brackets`.
//
// - Open `brackets` must be closed in the correct order.
//
// - Every close bracket has a corresponding open bracket of the same type.
package valid_parentheses
var (
brackets = map[rune]rune{
'(': ')',
'{': '}',
'[': ']',
}
)
// isValid
func byOpen(s string) bool {
opened := make([]rune, 0, len(s)/2)
for _, r := range s {
if _, ok := brackets[r]; ok {
opened = append(opened, r)
continue
}
if len(opened) == 0 {
return false
}
if r != brackets[opened[len(opened)-1]] {
return false
}
opened = append([]rune{}, opened[:len(opened)-1]...)
}
return len(opened) == 0
}
func byClose(s string) bool {
var closed []rune
for _, r := range s {
if c, ok := brackets[r]; ok {
closed = append(closed, c)
continue
}
if len(closed) == 0 {
return false
}
if r != closed[len(closed)-1] {
return false
}
closed = append([]rune{}, closed[:len(closed)-1]...)
}
return len(closed) == 0
}