Challenge
Write a function areCurlyBracesMatched
that takes in a string s
containing only {
and/or }
and returns true
if s
is properly matched, and false
otherwise.
A string s
is considered properly matched if the string is empty or if every open brace has a corresponding close brace.
Examples
{{}}
is properly matched.
{{{
is not properly matched.
{}{}{}
is properly matched.
areCurlyBracesMatched("{{{}{}}}"), true;
areCurlyBracesMatched("{{"), false;
areCurlyBracesMatched("{}}"), false;
areCurlyBracesMatched(""), true;
Happy coding!
This challenge comes from theonlydaryl on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Latest comments (35)
Python
My solution in js
Simple JS solution
Iterate through the string and count up when you encounter a "{" and down when not.
Check after every iteration, if the last character was a closing brace too much and return false if so.
Finally, return true when the amount of opening braces matches the amount of closing braces (i == 0).
Ahh, this old trick. I've done it for at least two interviewers this summer. Terrific way for them to determine how good I am at building Rails applications, but, I digress.
Functional JS with Tail Call Optimization (TCO)
Some F#
Perl solution.
Just remove all the
{}
s until there's nothing to remove. If you got an empty string, the input was valid.Damn, there is never any PHP solutions, I've to get to it !
With the examples given, this challenge is identical to Challenge 29: Xs and Os, because counting the braces suffice to get the answer.
If you add
areCurlyBracesMatched("}{"), false;
, though, it’s different.I think it’s a pity that the examples for a lot of these challenges are missing some important cases that would help when the explanation is not completely clear.
Let's see what you guys think...
C++
Rust:
Elegant JS solution
I love this one.
Here we Go!... I swear I'm funny sometimes
curly.go
curly_test.go
My take at the challenge written in Haskell.
Try it online.
Python solution