Skip to content

Instantly share code, notes, and snippets.

@ylegall
Created November 9, 2013 16:53
Show Gist options
  • Save ylegall/7387363 to your computer and use it in GitHub Desktop.
Save ylegall/7387363 to your computer and use it in GitHub Desktop.
balance parentheses
import java.util.*;
public class Test
{
static String balance(String input) {
int count = 0;
StringBuilder sb = new StringBuilder();
for (char c : input.toCharArray()) {
if (c == '(') {
++count;
sb.append(c);
} else if (c == ')') {
if (count - 1 >= 0) {
--count;
sb.append(c);
}
} else {
sb.append(c);
}
}
while (count > 0) {
sb.append(')');
--count;
}
return sb.toString();
}
static void test(String in) {
System.out.print(in + " => ");
System.out.println(balance(in));
}
public static void main(String[] args) {
test("()()()");
test("(()()");
test(")()()");
test("((()))");
test("((())");
test("(()))");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment