Created
November 9, 2013 16:53
-
-
Save ylegall/7387363 to your computer and use it in GitHub Desktop.
balance parentheses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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