-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path2116-check-if-a-parentheses-string-can-be-valid.py
More file actions
38 lines (35 loc) · 1015 Bytes
/
2116-check-if-a-parentheses-string-can-be-valid.py
File metadata and controls
38 lines (35 loc) · 1015 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# time complexity: O(n)
# space complexity: O(n)
class Solution:
def canBeValid(self, s: str, locked: str) -> bool:
if len(s) % 2:
return False
openBrackets = []
unlocked = []
for i in range(len(s)):
if locked[i] == '0':
unlocked.append(i)
elif s[i] == '(':
openBrackets.append(i)
elif s[i] == ')':
if openBrackets:
openBrackets.pop()
elif unlocked:
unlocked.pop()
else:
return False
while unlocked and openBrackets and openBrackets[-1] < unlocked[-1]:
unlocked.pop()
openBrackets.pop()
if openBrackets:
return False
return True
s = "))()))"
locked = "010100"
print(Solution().canBeValid(s, locked))
s = "()()"
locked = "0000"
print(Solution().canBeValid(s, locked))
s = ")"
locked = "0"
print(Solution().canBeValid(s, locked))