Skip to content

Instantly share code, notes, and snippets.

@bogdanovich
Last active July 16, 2016 05:15
Show Gist options
  • Save bogdanovich/fe66e733c7a6b14b4a9b26124fc3ab81 to your computer and use it in GitHub Desktop.
Save bogdanovich/fe66e733c7a6b14b4a9b26124fc3ab81 to your computer and use it in GitHub Desktop.
Balance parens
# Given a string with possibly unbalanced parentheses, return a string with balanced
# parentheses removing a minimal number of parentheses.
# Example: (abc)((),
# Output: (abc)()
def balance_parens(str)
stack = []
str.each_char.with_index do |char, i|
case char
when '('
stack.push([char, i])
when ')'
if !stack.empty? && stack.last[0] == '('
stack.pop
else
stack.push([char, i])
end
end
end
# only unbalanced parentheses are left in stack
stack.reverse_each do |key, position|
str[position] = ''
end
str
end
p balance_parens("(abc)(()")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment