File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Question Link: https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/
3
+ * Primary idea: Count the number of left brackets and append to result accordingly. Remove unnecessary left brackets from most right.
4
+ * Time Complexity: O(n), Space Complexity: O(1)
5
+ */
6
+
7
+ class MinimumRemoveMakeValidParentheses {
8
+ func minRemoveToMakeValid( _ s: String ) -> String {
9
+ var leftCount = 0 , res = Array ( " " )
10
+
11
+ for char in s {
12
+ if char == " ( " {
13
+ leftCount += 1
14
+ res. append ( char)
15
+ } else if char == " ) " {
16
+ if leftCount == 0 {
17
+ continue
18
+ } else {
19
+ leftCount -= 1
20
+ res. append ( char)
21
+ }
22
+ } else {
23
+ res. append ( char)
24
+ }
25
+ }
26
+
27
+ // remove unnecessary left bracket
28
+ if leftCount > 0 {
29
+ var i = res. count - 1
30
+
31
+ while i >= 0 {
32
+ if res [ i] == " ( " {
33
+ res. remove ( at: i)
34
+ leftCount -= 1
35
+
36
+ if leftCount == 0 {
37
+ break
38
+ }
39
+ }
40
+
41
+ i -= 1
42
+ }
43
+ }
44
+
45
+ return String ( res)
46
+ }
47
+ }
You can’t perform that action at this time.
0 commit comments