forked from oleg-cherednik/DailyCodingProblem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
36 lines (29 loc) · 858 Bytes
/
Solution.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
/**
* @author Oleg Cherednik
* @since 03.04.2019
*/
public class Solution {
public static void main(String... args) {
System.out.println(findBalancedString("(()")); // (());
System.out.println(findBalancedString("))()(")); // ()();
}
public static String findBalancedString(String str) {
StringBuilder buf = new StringBuilder();
int count = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == '(') {
count++;
buf.append('(');
} else if (ch == ')') {
if (count > 0) {
buf.append(')');
count--;
}
}
}
for (int i = 0; i < count; i++)
buf.append(')');
return buf.toString();
}
}