-
Notifications
You must be signed in to change notification settings - Fork 373
/
bracket_validator_test.go
86 lines (71 loc) · 1.78 KB
/
bracket_validator_test.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
/*
Problem:
- Given a string, determine if its brackets are properly nested.
Example:
- Input: "{[]()}"
Output: true
- Input: "{[(])}"
Output: false
- Input: "{[}"
Output: false
Approach:
- Use a stack to keep track of matching parenthesis as we iterate
through the string.
Solution:
- Iterate through the string, keep a stack to keep track of closing and
opening parenthesis.
- If we see an opener, push it to the stack.
- If we see an closer, pop from the stack if is the one for the opener at the
stop of stack.
Cost:
- O(n) time and O(n) space, where n is the number of operations.
*/
package interviewcake
import (
"testing"
"github.com/hoanhan101/algo/common"
)
func TestValidateBracket(t *testing.T) {
// define test cases.
tests := []struct {
sentence string
expected bool
}{
{"{[]()}", true},
{"{[(])}", false},
{"{[}", false},
}
for _, tt := range tests {
result := validateBracket(tt.sentence)
common.Equal(t, tt.expected, result)
}
}
func validateBracket(sentence string) bool {
// mapping of opening and closing brackets.
m := map[string]string{
"(": ")",
"{": "}",
"[": "]",
}
stack := []string{}
for _, char := range sentence {
// if it is an opener, push to the stack.
if common.ContainString([]string{"(", "{", "["}, string(char)) {
stack = append(stack, string(char))
} else if common.ContainString([]string{")", "}", "]"}, string(char)) {
// return false if the stack is empty.
if len(stack) == 0 {
return false
}
// pop to get the last item from the stack.
lastUnclosed := stack[len(stack)-1]
stack = stack[:len(stack)-1]
// return false if the last opening bracket doesn't match the
// current closing one.
if m[lastUnclosed] != string(char) {
return false
}
}
}
return len(stack) == 0
}