Last active
July 16, 2016 05:15
-
-
Save bogdanovich/fe66e733c7a6b14b4a9b26124fc3ab81 to your computer and use it in GitHub Desktop.
Balance parens
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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