balance parentheses

本文介绍了一种算法,用于处理带有括号的字符串,并通过移除最少的字符来达到括号平衡的目的。该方法分为两步:先从左到右去除多余的右括号,再从右到左去除多余的左括号,最终实现字符串中括号的平衡。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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;

	@Before
	public void setUp() throws Exception {
		sol = new Solution();
	}

	@Test
	public void test1() {
		assertEquals(sol.balance("()"), "()");	
	}
	@Test
	public void test2() {
		assertEquals(sol.balance(")("), "");
	}
	@Test
	public void test3() {
		assertEquals(sol.balance("((((("), "");
	}
	@Test
	public void test4() {
		assertEquals(sol.balance("()()"), "()()");
	}
	@Test
	public void test5() {
		assertEquals(sol.balance("(()())"), "(()())");
	}
	@Test
	public void test6() {
		assertEquals(sol.balance("(()()("), "()()");
	}
	@Test
	public void test7() {
		assertEquals(sol.balance("(())"), "(())");
	}
	@Test
	public void test8() {
		assertEquals(sol.balance(")(())("), "(())");
	}
	@Test
	public void test9() {
		assertEquals(sol.balance(")))"), "");
	}
	@Test
	public void test10() {
		assertEquals(sol.balance("()))"), "()");
	}
	@Test
	public void test11() {
		assertEquals(sol.balance("())()"), "()()");
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值