go: add «2116. Check if a Parentheses String Can Be Valid»
URL: https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
80974c503d
commit
61dfb7cbd5
1 changed files with 44 additions and 0 deletions
44
go/check-if-a-parentheses-string-can-be-valid.go
Normal file
44
go/check-if-a-parentheses-string-can-be-valid.go
Normal file
|
@ -0,0 +1,44 @@
|
|||
package main
|
||||
|
||||
func canBeValid(s string, locked string) bool {
|
||||
n := len(s)
|
||||
if n%2 == 1 {
|
||||
// can't pair brackets
|
||||
return false
|
||||
}
|
||||
|
||||
open, unlocked, balance := 0, 0, 0
|
||||
for i := range n {
|
||||
if locked[i] == '0' {
|
||||
unlocked++
|
||||
} else if s[i] == '(' {
|
||||
open++
|
||||
} else if s[i] == ')' {
|
||||
if open > 0 {
|
||||
open--
|
||||
} else if unlocked > 0 {
|
||||
unlocked--
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for i := n - 1; i >= 0 && (unlocked != 0 || open != 0); i-- {
|
||||
if locked[i] == '0' {
|
||||
balance--
|
||||
unlocked--
|
||||
} else if s[i] == '(' {
|
||||
balance++
|
||||
open--
|
||||
} else if s[i] == ')' {
|
||||
balance--
|
||||
}
|
||||
|
||||
if balance > 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return open <= 0
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue