Skip to content

Instantly share code, notes, and snippets.

@muxcmux
Last active January 23, 2020 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muxcmux/5dcd2d219db6b423ec4ca7517fe406f7 to your computer and use it in GitHub Desktop.
Save muxcmux/5dcd2d219db6b423ec4ca7517fe406f7 to your computer and use it in GitHub Desktop.
O(2n), samo che ne bachka, shtoto ne hvashta vryshta "))((" vmesto empty str
# @param {String} s
# @return {String}
def min_remove_to_make_valid(s)
chars = s.split('')
op = chars.reduce(0) { |a, c| a + (c == '(' ? 1 : 0) }
cl = chars.reduce(0) { |a, c| a + (c == ')' ? 1 : 0) }
diff = op - cl
chars.select do |c|
if diff === 0
true
elsif diff > 0
if c === '('
diff -= 1
false
else
true
end
else
if c === ')'
diff += 1
false
else
true
end
end
end.join('')
end
puts min_remove_to_make_valid("(a(b(c)d)")
puts min_remove_to_make_valid("lee(t(c)o)de)")
puts min_remove_to_make_valid("a)b(c)d")
puts min_remove_to_make_valid("))((")
puts min_remove_to_make_valid("(a(b(c)d)")
puts min_remove_to_make_valid("a(b(c)d)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment