Check if a Parentheses String Can Be Valid LeetCode solution in Python

1
# Runtime: 460 ms (Top 26.24%) | Memory: 15.4 MB (Top 86.61%)
2
class Solution:
3
def canBeValid(self, s: str, locked: str) -> bool:
4
def validate(s: str, locked: str, op: str) -> bool:
5
bal, wild = 0, 0
6
for i in range(len(s)):
7
if locked[i] == "1":
8
bal += 1 if s[i] == op else -1
9
else:
10
wild += 1
11
if wild + bal < 0:
12
return False
13
return bal <= wild
14

15
return (
16
len(s) % 2 == 0
17
and validate(s, locked, "(")
18
and validate(s[::-1], locked[::-1], ")")
19
)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0