Forked from jemise111/cli_balanced_delimiters.rb
Last active
August 29, 2015 14:10
-
-
Save tsyber1an/cea60b9bd2e723108823 to your computer and use it in GitHub Desktop.
This file contains 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 'Benchmark' | |
def balanced_delimiters?(text) | |
openers = [] | |
matchers = { | |
')' => '(', | |
']' => '[', | |
'}' => '{' | |
} | |
text.chars.each do |char| | |
if matchers.values.include?(char) | |
openers.push(char) | |
else | |
if openers.last == matchers[char] | |
openers.pop | |
else | |
return false | |
end | |
end | |
end | |
openers.empty? | |
end | |
# Sample Test Cases | |
# ------------------ | |
test_text = ['(){}', '([{}])', '({})', '([)]', '(', ')', '([})'] | |
test_text.each do |test| | |
puts balanced_delimiters?(test) | |
end | |
# Test Time Complexity | |
# --------------------- | |
test_text_2 = '({{([])}})' * 1_000 | |
test_text_3 = '({{([])}})' * 10_000 | |
test_text_4 = '({{([])}})' * 100_000 | |
puts Benchmark.measure { balanced_delimiters?(test_text_2) } | |
puts Benchmark.measure { balanced_delimiters?(test_text_3) } | |
puts Benchmark.measure { balanced_delimiters?(test_text_4) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment