Created
May 26, 2020 18:31
-
-
Save aksnell/1175a633afc93974fb0a81ff16119d89 to your computer and use it in GitHub Desktop.
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
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