本文主要是介绍balance parentheses,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
Given a string with parentheses, return a string with balanced parentheses by removing the fewest characters possible. You cannot add anything to the string.
Examples:
balance("()") -> "()"
balance(")(") -> "".
balance("(((((") -> ""
balance("(()()(") -> "()()"
balance(")(())(") -> "(())"
思路:从左往右一遍,去掉多余的右括号。从右往左一遍,去掉多余的左括号。
public class Solution {public String balance(String input) {if (input == null || input.isEmpty()) {return input;}String temp = removeRight(input);return removeLeft(temp);}private String removeLeft(String input) {StringBuffer result = new StringBuffer();int count = 0;for (int i = input.length() - 1; i >= 0; i--) {char ch = input.charAt(i);if (ch == ')') {result.append(')');count++;}else {if (count > 0) {result.append('(');count--;}}}return result.reverse().toString();}private String removeRight(String input) {StringBuffer result = new StringBuffer();int count = 0;for (int i = 0; i < input.length(); i++) {char ch = input.charAt(i);if (ch == '(') {result.append('(');count++;}else {if (count > 0) {result.append(')');count--;}}}return result.toString();}
}
public class TestSolution {private static Solution sol;@Beforepublic void setUp() throws Exception {sol = new Solution();}@Testpublic void test1() {assertEquals(sol.balance("()"), "()"); }@Testpublic void test2() {assertEquals(sol.balance(")("), "");}@Testpublic void test3() {assertEquals(sol.balance("((((("), "");}@Testpublic void test4() {assertEquals(sol.balance("()()"), "()()");}@Testpublic void test5() {assertEquals(sol.balance("(()())"), "(()())");}@Testpublic void test6() {assertEquals(sol.balance("(()()("), "()()");}@Testpublic void test7() {assertEquals(sol.balance("(())"), "(())");}@Testpublic void test8() {assertEquals(sol.balance(")(())("), "(())");}@Testpublic void test9() {assertEquals(sol.balance(")))"), "");}@Testpublic void test10() {assertEquals(sol.balance("()))"), "()");}@Testpublic void test11() {assertEquals(sol.balance("())()"), "()()");}
}
这篇关于balance parentheses的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!