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:
Matej Focko 2025-01-12 18:44:44 +01:00
parent 80974c503d
commit 61dfb7cbd5
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View 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
}