Given a string containing brackets []
, braces {}
, parentheses ()
,
or any combination thereof, verify that any and all pairs are matched
and nested correctly.
Follow the setup instructions for Crystal here:
http://exercism.io/languages/crystal
More help installing can be found here:
http://crystal-lang.org/docs/installation/index.html
Execute the tests with:
$ crystal spec
In each test suite all but the first test have been skipped.
Once you get a test passing, you can unskip the next one by changing pending
to it
.
Ginna Baker
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
require "spec"
require "../src/*"
describe "Brackets" do
describe "#are_valid?" do
it "paired square brackets" do
Brackets.are_valid?("[]").should be_true
end
it "empty string" do
Brackets.are_valid?("").should be_true
end
it "unpaired brackets" do
Brackets.are_valid?("[[").should be_false
end
it "wrong ordered brackets" do
Brackets.are_valid?("}{").should be_false
end
it "paired with whitespace" do
Brackets.are_valid?("{ }").should be_true
end
it "simple nested brackets" do
Brackets.are_valid?("{[]}").should be_true
end
it "several paired brackets" do
Brackets.are_valid?("{}[]").should be_true
end
it "paired and nested brackets" do
Brackets.are_valid?("([{}({}[])])").should be_true
end
it "unopened closing brackets" do
Brackets.are_valid?("{[)][]}").should be_false
end
it "unpaired and nested brackets" do
Brackets.are_valid?("([{])").should be_false
end
it "paired and wrong nested brackets" do
Brackets.are_valid?("[({]})").should be_false
end
it "math expression" do
Brackets.are_valid?("(((185 + 223.85) * 15) - 543)/2").should be_true
end
it "complex latex expression" do
Brackets.are_valid?("\left(\begin{array}{cc} \frac{1}{3} & x\\ \mathrm{e}^{x} &... x^2 \end{array}\right)").should be_true
end
end
end
module Brackets
PAIRS = {
']' => '[',
')' => '(',
'}' => '{'
}
def self.are_valid?(s : String) : Bool
a = [] of Char
s.each_char { |c|
pc = PAIRS[c]?
if PAIRS.values.includes?(c)
a.push(c)
elsif pc
if a.last? == nil || a.last != pc
return false
end
a.pop
end
}
a.empty?
end
end
A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.
Here are some questions to help you reflect on this solution and learn the most from it.
Community comments