balance parentheses

2024-05-07 12:18
文章标签 balance parentheses

本文主要是介绍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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/967332

相关文章

856. Score of Parentheses

856. Score of Parentheses class Solution:def scoreOfParentheses(self, s: str) -> int:stack=[]i=0for c in s:if c=='(':stack.append(c)else:score=0while stack[-1]!='(':score+=stack.pop()stack.pop()score

leetcode#32. Longest Valid Parentheses

题目 Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. For "(()", the longest valid parentheses substring is "()", wh

LeetCode - 32. Longest Valid Parentheses

32. Longest Valid Parentheses  Problem's Link  ---------------------------------------------------------------------------- Mean:  给定一个由'('和')'组成的字符串,求最长连续匹配子串长度. analyse: 定义一个stack<pair

LeetCode 22 Generate Parentheses

题意: 用n组小括号,生成所有满足括号匹配的序列。 思路: 我用了比较粗暴的方式,用set不断迭代答案,每次迭代使得括号组数+1直到n为止。 还有一种方法是dfs构造,因为长度已经确定,所以每个位置要么放(要么放),利用前缀和维护括号匹配即可。 代码: class Solution {public:vector <string> generateParenthesis

Leetcode90: Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()(

poj 1837 Balance 二维费用背包

题意: 给你c(2<=c<=20)个挂钩,g(2<=g<=20)个砝码,求在将所有砝码(砝码重1~~25)挂到天平(天平长 -15~~15)上,并使得天平平衡的方法数....... 思路:(这是我木有想到的)将g个挂钩挂上的极限值:15*25*20==7500 那么在有负数的情况下是-7500~~7500 以0为平衡点...... 那可以将平衡点往右移7500个单位,范围就是0~~1500

poj 1837 Balance(01背包 天平平衡)

题目大意: 有一个天平,天平左右两边各有若干个钩子,总共有C个钩子,有G个钩码,求将钩码全部挂到钩子上使天平平衡的方法的总数。 其中可以把天枰看做一个以x轴0点作为平衡点的横轴 输入: 2 4 //C 钩子数 与 G钩码数 -2 3 //负数:左边的钩子距离天平中央的距离;正数:右边的钩子距离天平中央的距离c[k] 3 4 5 8 //G个重物的质量w[i]

LeetCode第21题之Generate Parentheses(两种解法)

C++代码: 解法一(在LeetCode上运行效率高于解法二): #include <vector>#include <iostream>#include <string>using namespace std;class Solution {private:vector<string> res;public: //leftRemain保存还可以放左括号的数目,rightRemain

LeetCode第20题之Valid Parentheses

方法一:用栈实现 C++代码: #include <stack>#include <iostream>using namespace std;//Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.clas

Easy 5 Valid Parentheses(20)

Description Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid. The brackets must close in the correct order, “()” and “()[]{}” are