forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.go
54 lines (49 loc) · 982 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
48
49
50
51
52
53
54
func isValid(s string) bool {
stack := newStack()
for _, str := range s {
if str == '(' || str == '[' || str == '{' {
stack.push(byte(str))
} else if str == ')' {
if stack.pop() != (byte('(')) {
return false
}
} else if str == ']' {
if stack.pop() != (byte('[')) {
return false
}
} else if str == '}' {
if stack.pop() != (byte('{')) {
return false
}
}
}
return stack.size() == 0
}
type Stack struct {
data []byte
index int
}
func newStack() *Stack {
return &Stack{
data: make([]byte, 10),
}
}
func (s *Stack) pop() byte {
if s.index == 0 {
return 0
}
s.index--
r := s.data[s.index]
return r
}
func (s *Stack) push(b byte) {
if len(s.data) - 1 <= s.index {
newData := make([]byte, len(s.data))
s.data = append(s.data, newData[:]...)
}
s.data[s.index] = b
s.index++
}
func (s *Stack) size() int {
return s.index
}