Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'minitest/autorun'
- # detect if a string symbols are balanced
- # '[()]' => true
- # '({)' => false
- # '(([[]]))'
- class Algo
- TABLE = {
- '(' => ')',
- '[' => ']',
- '{' => '}'
- }
- OPENINGS = TABLE.keys
- def is_balanced str
- stack = []
- str.each_char do |char|
- if OPENINGS.include?(char)
- stack << char
- else
- open_char = stack.pop
- if !open_char or TABLE[open_char] != char
- return false
- end
- end
- end
- stack.empty? ? true : false
- end
- end
- describe Algo do
- before do
- @algo = Algo.new
- end
- describe "balanced symbols" do
- it "return true if symbols are balanced" do
- assert_equal true, @algo.is_balanced( '()' )
- assert_equal true, @algo.is_balanced( '[()]' )
- assert_equal true, @algo.is_balanced( '[[[({})]]]' )
- assert_equal true, @algo.is_balanced( '' )
- end
- it "return false if symbols are not balanced" do
- assert_equal false, @algo.is_balanced( '{()' )
- assert_equal false, @algo.is_balanced( '{' )
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement