Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8d2d02a

Browse files
author
Yeqi Tao
committed
Add Soulution.go for 0020.Valid Parentheses
1 parent 5d7e4aa commit 8d2d02a

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
func isValid(s string) bool {
2+
stack := newStack()
3+
for _, str := range s {
4+
if str == '(' || str == '[' || str == '{' {
5+
stack.push(byte(str))
6+
} else if str == ')' {
7+
if stack.pop() != (byte('(')) {
8+
return false
9+
}
10+
} else if str == ']' {
11+
if stack.pop() != (byte('[')) {
12+
return false
13+
}
14+
} else if str == '}' {
15+
if stack.pop() != (byte('{')) {
16+
return false
17+
}
18+
}
19+
}
20+
return stack.size() == 0
21+
}
22+
23+
type Stack struct {
24+
data []byte
25+
index int
26+
}
27+
28+
func newStack() *Stack {
29+
return &Stack{
30+
data: make([]byte, 10),
31+
}
32+
}
33+
34+
func (s *Stack) pop() byte {
35+
if s.index == 0 {
36+
return 0
37+
}
38+
s.index--
39+
r := s.data[s.index]
40+
return r
41+
}
42+
43+
func (s *Stack) push(b byte) {
44+
if len(s.data) - 1 <= s.index {
45+
newData := make([]byte, len(s.data))
46+
s.data = append(s.data, newData[:]...)
47+
}
48+
s.data[s.index] = b
49+
s.index++
50+
}
51+
52+
func (s *Stack) size() int {
53+
return s.index
54+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /