This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
/
BalanceParentheses.cs
84 lines (71 loc) · 2.07 KB
/
BalanceParentheses.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CS.Problems.Miscellaneous
{
public class BalanceParentheses
{
/// <summary>
/// O(n) time complexity
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string Balance(string text)
{
var result = new StringBuilder();
for (int i = 0; i < text.Length; i++)
{
var progress = Balance(text, i, result);
if (progress == i)
{
continue;
}
i = progress;
}
return result.ToString();
}
/// <summary>
/// Recursively visit child parentheses and add balanced items to result
/// </summary>
/// <param name="text"></param>
/// <param name="i"></param>
/// <param name="result"></param>
/// <returns></returns>
public static int Balance(string text, int i, StringBuilder result)
{
if (i >= text.Length)
{
return text.Length;
}
//close parentheses
if (text[i] == ')')
{
return i;
}
//a character
if (text[i] != '(' && text[i] != ')')
{
result.Append(text[i]);
return Balance(text, i + 1, result);
}
//open parenthesis
var subResult = new StringBuilder();
while (i + 1 < text.Length && text[i] == '(')
{
i = Balance(text, i + 1, subResult);
if (i < text.Length && text[i] == ')')
{
result.Append("(" + subResult.ToString() + ")");
}
else
{
result.Append(subResult.ToString());
}
subResult.Clear();
i++;
}
return i;
}
}
}