Implement a function string balanceParanthesis(string s); which given a string s consisting of some parenthesis returns a string s1 in which parenthesis are balanced and differences between s and s1 are minimum. Eg - "(ab(xy)u)2)" -> "(ab(xy)u)2" ")))(((" -> ""
Anonymous
def balanceParanthesis(str) : (bef, aft, left, right) = (0, 0, 0, 0) for i in str : if i == '(' : if right > 0 : bef += right right = 0 left += 1 elif i == ')' : if left > 0 : left -= 1 else : right += 1 if right > 0 : bef += right if left > 0 : aft = left return '(' * bef + str + ')' * aft
Check out your Company Bowl for anonymous work chats.