Coding for Scrubs: Checking for Pairs (, {, [ (Ruby)

Problem:

Pseudocode:

1. Define opening tags
2. Define unpaired tags
3. Iterate forward through string
4. Impossible to fail on an opener until you reach the end of the string. Can only fail on a closer
5. Simply track the openers and only scrutinize the closers

Let’s Code!

def isBalanced(string)
openers = ["(", "[", "{"]
unpaired = []
end
def isBalanced(string)
openers ["(", "[", "{"]
unpaired = []
string.split('').each do |char|
if openers.include?(char)
unpaired << char
else
partner = unpaired.pop
case char
when ")"
if partner != "("
return false
end
when "]"
if partner != "["
return false
end
when "}"
if partner != "{"
return false
end
else
return nil
end
end
end
def isBalanced(string)
openers ["(", "[", "{"]
unpaired = []
string.split('').each do |char|
if openers.include?(char)
unpaired << char
else
partner = unpaired.pop
case char
when ")"
if partner != "("
return false
end
when "]"
if partner != "["
return false
end
when "}"
if partner != "{"
return false
end
else
return nil
end
end
end
if unpaired.size == 0
return true
end
end

Software Engineer in the making.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store