Skip to content

Instantly share code, notes, and snippets.

@mikhailov
Last active September 26, 2015 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikhailov/c31607958a4703622217 to your computer and use it in GitHub Desktop.
Save mikhailov/c31607958a4703622217 to your computer and use it in GitHub Desktop.
ValidParentheses
class ValidParentheses
SYMBOLS = {"(" => ")", "[" => "]", "{" => "}"}
def initialize(array)
@array = array.split("")
@stack = []
end
def process
@array.each do |i|
if SYMBOLS.keys.include?(i)
@stack.push(i)
elsif SYMBOLS.values.include?(i)
if @stack.last == SYMBOLS.key(i)
@stack.pop
else
return false
end
end
end
return !@stack.empty? ? false : true
end
end
require 'minitest/autorun'
class TestValidParentheses < Minitest::Unit::TestCase
def test_valid_input_1
assert_equal ValidParentheses.new("()").process, true
end
def test_valid_input_2
assert_equal ValidParentheses.new("()[]{}").process, true
end
def test_valid_input_3
assert_equal ValidParentheses.new("()([]){[()]}").process, true
end
def test_valid_input_4
assert_equal ValidParentheses.new("[()[]{}]").process, true
end
def test_invalid_input_5
assert_equal ValidParentheses.new("(]").process, false
end
def test_invalid_input_6
assert_equal ValidParentheses.new("([)]").process, false
end
def test_invalid_input_7
assert_equal ValidParentheses.new("()[)()]").process, false
end
def test_invalid_input_8
assert_equal ValidParentheses.new("[()[]{}](").process, false
end
def test_invalid_input_9
assert_equal ValidParentheses.new("[()[]{}]([[[").process, false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment