File tree 1 file changed +22
-45
lines changed
1 file changed +22
-45
lines changed Original file line number Diff line number Diff line change 1
1
package valid_parentheses
2
2
3
3
func isValid (s string ) bool {
4
- if len (s )% 2 != 0 {
5
- return false
6
- }
7
- left := map [byte ]struct {}{
8
- '(' : struct {}{},
9
- '[' : struct {}{},
10
- '{' : struct {}{},
11
- }
12
- right := map [byte ]struct {}{
13
- ')' : struct {}{},
14
- ']' : struct {}{},
15
- '}' : struct {}{},
16
- }
17
- bytes := []byte (s )
18
- stack := []byte {}
19
- for i := range bytes {
20
- if _ , ok := left [bytes [i ]]; ok {
21
- stack = append (stack , bytes [i ])
22
- } else if _ , ok = right [bytes [i ]]; ok {
23
- if len (stack ) == 0 {
24
- return false
25
- }
26
- switch stack [len (stack )- 1 ] {
27
- case '(' :
28
- if bytes [i ] != ')' {
29
- return false
30
- }
31
- case '[' :
32
- if bytes [i ] != ']' {
33
- return false
34
- }
35
- case '{' :
36
- if bytes [i ] != '}' {
37
- return false
38
- }
39
- }
40
- stack = stack [:len (stack )- 1 ]
41
- } else {
42
- return false
43
- }
44
- }
45
- if len (stack ) == 0 {
46
- return true
47
- }
48
- return false
4
+ m := map [rune ]rune {
5
+ '(' : ')' ,
6
+ '[' : ']' ,
7
+ '{' : '}' ,
8
+ }
9
+ stack := make ([]rune , len (s ))
10
+ top := 0
11
+ for _ , c := range s {
12
+ switch c {
13
+ case '(' , '[' , '{' :
14
+ stack [top ] = m [c ]
15
+ top ++
16
+ case ')' , ']' , '}' :
17
+ if top > 0 && stack [top - 1 ] == c {
18
+ top --
19
+ } else {
20
+ return false
21
+ }
22
+ }
23
+ }
24
+
25
+ return top == 0
49
26
}
You can’t perform that action at this time.
0 commit comments