Skip to content

Commit d1eb315

Browse files
authored
Merge pull request #341 from soapyigu/Array
Add a solution to Minimum Remove to Make Valid Parentheses
2 parents 4923019 + b1c1326 commit d1eb315

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
}

0 commit comments

Comments
 (0)