File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ package hello
2+
3+ import (
4+ "strings"
5+ )
6+
7+ const (
8+ openChar = "({["
9+ closeChar = ")]}"
10+ )
11+
12+ func isValid (s string ) bool {
13+ ss := strings .Split (s , "" )
14+ stack := []string {}
15+
16+ // If the very first one is not an opening character,
17+ // no need to check followings
18+ if ! strings .Contains (openChar , ss [0 ]) || ! strings .Contains (closeChar , ss [len (ss )- 1 ]) {
19+ return false
20+ }
21+
22+ // If the length is not even, there is an incomplete pair
23+ if len (ss )% 2 == 1 {
24+ return false
25+ }
26+
27+ // Loop over the slice to check
28+ // - If the current one is an opening one, then push into the stack
29+ // - If the current one is a closing one, then pop and compare with the previous one from the stack
30+ for _ , c := range ss {
31+ if strings .Contains (openChar , c ) {
32+ stack = append (stack , c )
33+ } else if strings .Contains (closeChar , c ) {
34+ if len (stack ) == 0 {
35+ return false
36+ }
37+ prev := stack [len (stack )- 1 ]
38+
39+ switch {
40+ case prev == "(" && c == ")" :
41+ fallthrough
42+ case prev == "[" && c == "]" :
43+ fallthrough
44+ case prev == "{" && c == "}" :
45+ stack = stack [:len (stack )- 1 ]
46+ default :
47+ stack = append (stack , c )
48+ }
49+ } else {
50+ // In case of non-parenthesis character found
51+ return false
52+ }
53+ }
54+ return len (stack ) == 0
55+ }
You can’t perform that action at this time.
0 commit comments