Facebook interview - String with Balanced 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(")(())(") -> "(())"

public String balance(String s) {
	int n = s.length();
	int start = n, end = 0;
	Stack<Integer> stack = new Stack<>();
	for(int i=0; i<n; i++) {
		int c = s.charAt(i);
		if(stack.isEmpty() || c == '(') {
			stack.push(i);
		} else {
			int top = stack.peek();
			if(s.charAt(top) == ')') {
				stack.push(i);
			} else {
				stack.pop();
				start = Math.min(start, top);
				end = Math.max(end, i);
			}
		}
	}
	return start>=end ? "" : s.substring(start, end+1);
}

可惜以上代码是不对的,不能解决“()(()”的情况,此时应该输出“()()”。

(()()((()()))”时应该输出“()()((()()))”或者“(())((()()))”。

修改代码如下:

public String balance(String s) {
	Stack<Integer> stack = new Stack<>();
	StringBuilder sb = new StringBuilder(s);
	for(int i=0; i<s.length(); i++) {
		int c = s.charAt(i);
		if(stack.isEmpty() || c == '(') {
			stack.push(i);
		} else {
			int top = stack.peek();
			if(s.charAt(top) == ')') {
				stack.push(i);
			} else {
				stack.pop();
			}
		}
	}
	while(!stack.isEmpty()) {
		sb.deleteCharAt(stack.pop());
	}
	return sb.toString();
}

猜你喜欢

转载自yuanhsh.iteye.com/blog/2194538