Challenge: Balanced Brackets
Complete this challenge with any kind of Java interop.
We'll cover the following
Description
The Balanced Brackets challenge is strongly aligned with Clojure. Its main idea is to validate if a composition of brackets is valid, similar to our coding style in Clojure, i.e., for each bracket that’s open, we want to have a corresponding one that’s closed. So, the challenge revolves around ensuring balanced combinations of the three types of brackets shown below:
()
[]
{}
However, what you’re going to test is not those simple combinations. We want to validate a sequence of balanced brackets and check if they’re valid.
Examples
[{}()]()
: This is a balanced bracket structure. We’re first opening with[
, then we have two combined pairs of{}
and()
, and then we close with]
. Finally, we have a pair of()
.([{}])
: This is also a balanced bracket structure. We have the pairs opening and closing in order.([{]})
: This is not a balanced bracket structure. We opened the three types of brackets, but then, instead of closing the last one, which was}
, we tried to close the]
. So, we invalidated the balanced brackets structure.
So, in this challenge, you’re going to implement a function that will check if a string containing a bracket structure is balanced or not. The function will be called balanced-brackets?
and will receive a single argument that’s a string. We want it to return a boolean with the response to the sequence of brackets we delivered.
The call to this function will be (balanced-brackets? "[{}()]()")
, and it will return true
.
As an initial hint to transform your string into a vector with the elements one by one, you can use Clojure’s split
function with the following regex:
Get hands-on with 1400+ tech skills courses.