Created
October 19, 2017 07:47
-
-
Save sitano/7db8058d31e30cfedd4c10711fa01193 to your computer and use it in GitHub Desktop.
parallel brackets sequence verification
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type res struct { | |
s []byte | |
l int | |
r int | |
} | |
func (r res) String() string { | |
return fmt.Sprint(string(r.s), " ", r.l, r.r) | |
} | |
func check(s []byte) res { | |
var l, r, c int | |
for i := 0; i < len(s); i++ { | |
b := s[i] | |
if b == '[' { | |
if c < 0 { | |
l += -c | |
c = 0 | |
} | |
c++ | |
} else { | |
c-- | |
} | |
} | |
if c > 0 { | |
r += c | |
} else { | |
l += -c | |
} | |
return res{s, l, r} | |
} | |
func merge(rs []res) bool { | |
c := 0 | |
for _, r := range rs { | |
c += r.r - r.l | |
if c < 0 { | |
return false | |
} | |
} | |
return c == 0 | |
} | |
func printCheck(s string) { | |
fmt.Println(check([]byte(s))) | |
} | |
func printMerge(s []string) { | |
rs := make([]res, 0, len(s)) | |
fmt.Println("new test") | |
for _, t := range s { | |
rs = append(rs, check([]byte(t))) | |
fmt.Println(rs[len(rs)-1]) | |
} | |
fmt.Println(merge(rs)) | |
} | |
func main() { | |
printCheck("[]") | |
printCheck("][") | |
printCheck("][][") | |
printCheck("[") | |
printCheck("]") | |
printCheck("][]") | |
printCheck("[][") | |
printCheck("]]][][[[[]]") | |
printMerge([]string{"["}) | |
printMerge([]string{"]"}) | |
printMerge([]string{"[", "]"}) | |
printMerge([]string{"]", "["}) | |
printMerge([]string{"]", "[]", "["}) | |
printMerge([]string{"[", "[]", "]"}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment