Skip to content

Instantly share code, notes, and snippets.

@absk1317
Last active May 30, 2018 20:00
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 absk1317/a2351d86fa3110506cc2f5866629ca7f to your computer and use it in GitHub Desktop.
Save absk1317/a2351d86fa3110506cc2f5866629ca7f to your computer and use it in GitHub Desktop.
String balance check whether for brackets
require 'pry'
PAIRS = {
'{' => '}',
'[' => ']',
'(' => ')'
}.freeze
def balanced?(string)
return false if string.length.odd?
return false if string =~ /[^\[\]\(\)\{\}]/
stack = []
push_and_pop string, stack
stack.empty?
end
def push_and_pop string, stack
string.chars do |bracket|
if expectation = PAIRS[bracket]
stack << expectation
else
return false unless stack.pop == bracket
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment