Skip to content

Instantly share code, notes, and snippets.

@brianbianco
Last active August 29, 2015 14:11
Show Gist options
  • Save brianbianco/46af6e2281961f7ba794 to your computer and use it in GitHub Desktop.
Save brianbianco/46af6e2281961f7ba794 to your computer and use it in GitHub Desktop.
Balanced String?
module BalancedString
OPENERS = ['(','[','{']
CLOSERS = [')',']','}']
def self.matching_pair?(opener,closer)
OPENERS.index(opener) == CLOSERS.index(closer)
end
def self.is_balanced?(string)
mystack = Array.new
string.each_char do |c|
if OPENERS.include? c
mystack.push c
elsif CLOSERS.include? c
return false unless matching_pair? mystack.pop, c
end
end
mystack.size == 0 ? true : false
end
end
t = ['{}','{[]}','{5}','a']
f = ['([)]','{[]']
strings = t + f
strings.each { |s| puts "Is #{s} balanced? #{BalancedString.is_balanced?(s)}" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment