Last active
August 29, 2015 14:11
-
-
Save brianbianco/46af6e2281961f7ba794 to your computer and use it in GitHub Desktop.
Balanced String?
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
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