xamples
epeat
ode
pproach
ptimize
est
One of your colleagues insists on writing all code in Notepad, resulting in code that won't run because the brackets, braces, and parenthesis are not properly balanced. You decide to write a bracket validator to check whether the brackets /braces/ parenthesis are valid.
[ ] ( ) { }
Given an input string return a boolean stating whether or not the brackets are balanced.
What are the expected outputs for each of these?
"{ [ ] ( ) }"
"{ [ ( ] ) }"
"{ [ }"
"{ [ text ( [ is { ( )[ totes]{ f } i } n ] e ) ] }"
{ [ ( ( ) )] }
{ [ ( ( ) )] }
{
{ [ ( ( ) )] }
{
{
[
{ [ ( ( ) )] }
{
{
[
(
{ [ ( ( ) )] }
{
{
[
(
(
{ [ ( ( ) )] }
{
{
[
(
(
)
{ [ ( ( ) )] }
The top bracket closes the one below it, so we can pop them off
{
[
(
(
)
{ [ ( ( ) )] }
{
(
[
{ [ ( ( ) ) ] }
{
(
)
The top bracket closes the one below it so pop it
[
{ [ ( ( ) )] }
{
[
{ [ ( ( ) ) ] }
{
{
[
]
The top bracket closes the one below it so pop it
{ [ ( ( ) ) ] }
{
{ [ ( ( ) ) ] }
{
{
The top bracket closes the one below it so pop it
}
{ [ ( ( ) ) ] }
We have checked every bracket in the input and since we have no unmatching brackets, we know that the brackets were balanced
What data structure did this approach remind you of ?
What data structure did this approach remind you of ?
a STACK!