Created
February 18, 2021 21:54
-
-
Save felipero/4203abd09821fdc8215e940c1fb775a4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class BracketsChecker | |
OPENING = ['[', '{', '('] | |
CLOSING_MAP = {'[' => ']', '{' => '}', '(' => ')'} | |
def valid?(input) | |
return false if input.empty? | |
open_brackets = [] | |
input.each_char do |char| | |
open_brackets << char if OPENING.include? char | |
last_open = open_brackets[-1] | |
open_brackets.pop if CLOSING_MAP[last_open] == char | |
end | |
open_brackets.empty? | |
end | |
end |
This file contains hidden or 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
require 'rspec' | |
require './brackets' | |
RSpec.describe BracketsChecker do | |
subject(:checker) { BracketsChecker.new } | |
it {expect(checker.valid?("(a[0]+b[2c[6]]) {24 + 53}")).to be true } | |
it {expect(checker.valid?("f(e(d))")).to be true } | |
it {expect(checker.valid?("[()]{}([])")).to be true } | |
it {expect(checker.valid?("((b)")).to be false } | |
it {expect(checker.valid?("(c]")).to be false } | |
it {expect(checker.valid?("{(a[])")).to be false } | |
it {expect(checker.valid?("([)]")).to be false } | |
it {expect(checker.valid?(")(")).to be false } | |
it {expect(checker.valid?("")).to be false } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment