Created
January 16, 2015 01:02
-
-
Save tlehman/ab4c06f86be5a12d1870 to your computer and use it in GitHub Desktop.
paren balancing
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
# 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