Problem · String
Balancing Parentheses
Given a string that consists of left and right parentheses, '(' and ')', balance the parentheses by inserting parentheses as necessary. Determine the minimum number of characters that must be inserted.
Complete the function balanceParentheses in the editor.
balanceParentheses has the following parameter:
String s: a string of parentheses
Returns
int: the minimum number of insertions needed
♫⋆。♪ ₊˚♬ ゚.Huge Thanks to spike!!𓂃 🐳𓈒𓏸
Examples
01 · Example 1
s = "()))" return = 2
Insert a '(' 2 times at the beginning of the string to make it valid: '((()))'
02 · Example 2
s = "))(("
return = 4Insert 2 left parentheses at the start and 2 right parentheses at the end of the string to get "(()))(())" after 4 insertions.
03 · Example 3
s = "(()))" return = 1
Insert 1 left paranthesis at the left end of the string to get '((()))'. The string is balanced after 1 insertion.
04 · Example 4
s = "()()" return = 0
The sequence is already valid.
Constraints
1 ≤ length of s ≤ 105
More Oracle problems
public int balanceParentheses(String s) {
// write your code here
}
s"()))"
expected2
sign in to submit