File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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
+ ```
You can’t perform that action at this time.
0 commit comments