Skip to content

Instantly share code, notes, and snippets.

@dharshan
Created December 26, 2022 03:27
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 dharshan/c8055f31f261d45c3ee314829b78e7a4 to your computer and use it in GitHub Desktop.
Save dharshan/c8055f31f261d45c3ee314829b78e7a4 to your computer and use it in GitHub Desktop.
Ruby bracket matching using stack
class BracketDemo
def solution(str)
valid = true
stack = []
str.each_char do |char|
case char
when '[', '{', '('
stack.push(char)
when ']'
last = stack.pop
valid = false if last != '['
when ')'
last = stack.pop
valid = false if last != '('
when '}'
last = stack.pop
valid = false if last != '{'
end
end
valid && stack.empty? ? 1 : 0
end
end
puts BracketDemo.new.solution("[]}()")
puts BracketDemo.new.solution("[]{}()")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment