Skip to content

Commit

Permalink
Create balanced_string.rb
Browse files Browse the repository at this point in the history
  • Loading branch information
absk1317 authored Oct 12, 2018
1 parent 890f552 commit 0358dae
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions balanced_string.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
def balanced?(string)
return false if string.length.odd?
return false if string =~ /[^\[\]\(\)\{\}]/

pairs = { '{' => '}', '[' => ']', '(' => ')' }

stack = []
string.chars do |bracket|
if expectation = pairs[bracket]
stack << expectation
else
return false unless stack.pop == bracket
end
end

stack.empty?
end

0 comments on commit 0358dae

Please sign in to comment.