-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1249-MinimumRemoveToMakeValidParentheses.cs
39 lines (35 loc) · 1.14 KB
/
1249-MinimumRemoveToMakeValidParentheses.cs
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
//-----------------------------------------------------------------------------
// Runtime: 96ms
// Memory Usage: 40.5 MB
// Link: https://leetcode.com/submissions/detail/369950110/
//-----------------------------------------------------------------------------
using System.Linq;
using System.Text;
namespace LeetCode
{
public class _1249_MinimumRemoveToMakeValidParentheses
{
public string MinRemoveToMakeValid(string s)
{
var sb = RemoveInvalidClosing(s.ToArray(), '(', ')');
sb = RemoveInvalidClosing(sb.ToString().Reverse().ToArray(), ')', '(');
return new string(sb.ToString().Reverse().ToArray());
}
private StringBuilder RemoveInvalidClosing(char[] s, char open, char close)
{
var sb = new StringBuilder();
int balance = 0;
foreach (var ch in s)
{
if (ch == open) balance++;
if (ch == close)
{
if (balance == 0) continue;
balance--;
}
sb.Append(ch);
}
return sb;
}
}
}