Last active
July 22, 2020 14:29
-
-
Save DNA/4ff32440f41b0caed36936828f7ba686 to your computer and use it in GitHub Desktop.
Code test
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
#! /usr/bin/env ruby | |
# Write a function that returns true if the brackets in a given string are balanced. | |
# Balanced means that every parenthesis/bracket or brace that is opened must be closed | |
# And it must be closed in the right order (Always close the last symbol you opened) | |
# The function must handle parens (), square brackets [], and curly braces {}. | |
# "(a[0]+b[2c[6]]) {24 + 53}" should return true | |
# "f(e(d))" should return true | |
# "[()]{}([])" should return true | |
# "((b)" should return false | |
# "(c]" should return false | |
# "{(a[])" should return false | |
# "([)]" should return false | |
# ")(" should return false | |
# "" should return false | |
class Char | |
def initialize(char) | |
@char = char | |
end | |
def bracket? | |
%w[{ } [ ] ( )].include? @char | |
end | |
def open? | |
%W[{ \[ (].include? @char | |
end | |
def inverse | |
{ | |
'(' => ')', | |
')' => '(', | |
'{' => '}', | |
'}' => '{', | |
'[' => ']', | |
']' => '[' | |
}[@char] | |
end | |
def to_s | |
@char | |
end | |
end | |
def parse_brackets(input) | |
return false if input.empty? | |
stack = [] | |
input.chars.each do |char| | |
char = Char.new(char) | |
next unless char.bracket? | |
if char.open? | |
stack << char | |
elsif stack.last.to_s == char.inverse | |
stack.pop | |
else | |
return false | |
end | |
end | |
stack.empty? | |
end | |
pp parse_brackets('(a[0]+b[2c[6]]) {24 + 53}') | |
pp parse_brackets('f(e(d))') | |
pp parse_brackets('[()]{}([])') | |
pp !parse_brackets('((b)') | |
pp !parse_brackets('(c]') | |
pp !parse_brackets('{(a[])') | |
pp !parse_brackets('([)]') | |
pp !parse_brackets(')(') | |
pp !parse_brackets('') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment