Skip to content

Instantly share code, notes, and snippets.

@aksnell
Created May 26, 2020 18:31
Show Gist options
  • Save aksnell/1175a633afc93974fb0a81ff16119d89 to your computer and use it in GitHub Desktop.
Save aksnell/1175a633afc93974fb0a81ff16119d89 to your computer and use it in GitHub Desktop.
func hasForwardMatch(target string, index int) bool {
matchStack := 1
for i := index + 1; i < len(target); i++ {
if target[i] == '(' {
matchStack++
} else {
matchStack--
if matchStack == 0 {
return true
}
}
}
return matchStack == 0
}
func hasBackwardMatch(target string, index int) bool {
matchStack := 1
for i := index - 1; i > -1; i-- {
if target[i] == ')' {
matchStack++
} else {
matchStack--
if matchStack == 0 {
return true
}
}
}
return matchStack == 0
}
func ValidParentheses(parens string) bool {
if len(parens) == 1 { return false }
recChan := make(chan bool)
numRoutines := 0
for i := range parens {
numRoutines++
if parens[i] == '(' {
go func(i int) {
recChan <- hasForwardMatch(parens, i)
}(i)
} else {
go func(i int) {
recChan <- hasBackwardMatch(parens, i)
}(i)
}
}
for i := 0; i < numRoutines; i++ {
if valid := <-recChan; !valid {
return false
}
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment