Skip to content

Commit b1ea733

Browse files
committed
921
1 parent f390254 commit b1ea733

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

TP/921.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
## 921 Minimum Add to Make Parentheses Valid
2+
3+
#### Description
4+
5+
[link](https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/)
6+
7+
---
8+
9+
#### Solution
10+
11+
left records the number of ( we need to add on the left of S.
12+
right records the number of ) we need to add on the right of S,
13+
which equals to the number of current opened parentheses.
14+
15+
16+
Loop char c in the string S:
17+
if (c == '('), we increment right,
18+
if (c == ')'), we decrement right.
19+
When right is already 0, we increment left
20+
Return left + right in the end
21+
22+
---
23+
24+
#### Code
25+
26+
O(n)
27+
O(n)
28+
29+
```python
30+
def minAddToMakeValid(self, S):
31+
left = right = 0
32+
for i in S:
33+
if right == 0 and i == ')':
34+
left += 1
35+
else:
36+
right += 1 if i == '(' else -1
37+
return left + right
38+
```

0 commit comments

Comments
 (0)