summaryrefslogtreecommitdiff
path: root/unit/01/matched_string.rb
diff options
context:
space:
mode:
authormo khan <mo.khan@gmail.com>2020-05-18 15:15:04 -0600
committermo khan <mo.khan@gmail.com>2020-05-18 15:15:04 -0600
commit623a5cc389f21bc7974ee5a53a506cb8a95f3f03 (patch)
treea927c4e3ed79bfe11495f1e014c81350516ce4f2 /unit/01/matched_string.rb
parent5743e4c4f4d2274e9f06d6a72e06b80fbc4a8f1a (diff)
re-arrange folders
Diffstat (limited to 'unit/01/matched_string.rb')
-rw-r--r--unit/01/matched_string.rb51
1 files changed, 51 insertions, 0 deletions
diff --git a/unit/01/matched_string.rb b/unit/01/matched_string.rb
new file mode 100644
index 0000000..2836d16
--- /dev/null
+++ b/unit/01/matched_string.rb
@@ -0,0 +1,51 @@
+require 'bundler/inline'
+
+gemfile do
+ source 'https://rubygems.org'
+
+ gem 'minitest'
+end
+
+require 'minitest/autorun'
+
+=begin
+A matched string is a sequence of {, }, (, ), [, and ] characters that are properly matched.
+For example, “{{()[]}}” is a matched string, but this “{{()]}” is not, since the second { is matched with a ].
+Show how to use a stack so that, given a string of length n, you can determine if it is a matched string in O(n) time.
+=end
+
+class Example < Minitest::Test
+ def matches?(open, close)
+ case open
+ when '('
+ return close == ')'
+ when '{'
+ return close == '}'
+ when '['
+ return close == ']'
+ else
+ raise [open, close].inspect
+ end
+ end
+
+ def matched_string?(string)
+ stack = []
+ string.chars.each do |char|
+ case char
+ when '{', '[', '('
+ stack.push(char)
+ else
+ return unless matches?(stack.pop, char)
+ end
+ end
+ stack.size.zero?
+ end
+
+ def test_valid
+ assert matched_string?("{{()[]}}")
+ end
+
+ def test_invalid
+ refute matched_string?("{{()]}")
+ end
+end