-
Notifications
You must be signed in to change notification settings - Fork 5
/
MinimumRemoveToMakeValidParentheses.java
47 lines (44 loc) · 1.24 KB
/
MinimumRemoveToMakeValidParentheses.java
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
39
40
41
42
43
44
45
46
47
/*https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/*/
class Solution {
public String minRemoveToMakeValid(String s) {
int count = 0, index = 0, n = s.length();
char[] arr = s.toCharArray();
//forward direction, deleting extra closing brackets
while (index < n)
{
if (arr[index] == '(') ++count;
else if (arr[index] == ')')
{
--count;
if (count < 0)
{
arr[index] = '\0';
count = 0;
}
}
++index;
}
//reverse direction, deleting extra opening brackets
index = n-1;
count = 0;
while (index >= 0)
{
if (arr[index] == ')') ++count;
else if (arr[index] == '(')
{
--count;
if (count < 0)
{
arr[index] = '\0';
count = 0;
}
}
--index;
}
StringBuilder result = new StringBuilder("");
for (char ch : arr)
if (ch != '\0')
result.append(ch);
return result.toString();
}
}