2015年10月11日星期日

return a string with balanced parentheses by removing the fewest characters possible

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(")(())(") -> "(())"

balance(")(())(") != "()()


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

没有评论:

发表评论