Created
April 22, 2024 21:22
-
-
Save leandronsp/07503f074abe02bb63cb02e6cecb1bbf to your computer and use it in GitHub Desktop.
LeetPolvo
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
# ruby 3+ | |
# gem install test-unit | |
require 'test/unit/assertions' | |
include Test::Unit::Assertions | |
def balanced?(input) | |
delimiters = { | |
"(" => ")", | |
"{" => "}", | |
"[" => "]" | |
} | |
stack = [] | |
for char in input.chars | |
case char | |
when *delimiters.keys | |
stack.push(char) | |
when *delimiters.values | |
return false if delimiters[stack.pop] != char | |
end | |
end | |
stack.size == 0 | |
end | |
assert balanced?("abc") | |
assert balanced?("(abc)") | |
assert balanced?("(ab(c))") | |
assert balanced?("(abc)d") | |
assert balanced?("(abc[%def])") | |
assert balanced?("$(abc[de]fg{hi}jk)%//") | |
refute balanced?("(abc") | |
refute balanced?("(ab(c)") | |
refute balanced?("abcd]") | |
refute balanced?("(abc]d") | |
refute balanced?("(({abc})") | |
refute balanced?("(ab[cd)ef]") | |
refute balanced?("{ab(cd}ef)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment