Skip to content

Instantly share code, notes, and snippets.

@tlehman
Created January 16, 2015 01:02
Show Gist options
  • Save tlehman/ab4c06f86be5a12d1870 to your computer and use it in GitHub Desktop.
Save tlehman/ab4c06f86be5a12d1870 to your computer and use it in GitHub Desktop.
paren balancing
# Balanced paren strings have the property that each opening ( has a closing ).
# This proceeds by scanning left to right, using a stack to keep track of open
# parens.
def balanced?(string)
characters = string.split(//)
stack = []
characters.each do |c|
stack.push(c) if c == "("
return false if stack.empty? and c == ")"
stack.pop if c == ")"
end
return stack.empty?
end
["()", "()()", "(()(()))", "()()()", "((((()))))",
")", "()(()", "(()))", "((((())))", "(()()))"].each do |s|
puts "#{s} : #{balanced?(s)}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment