In this lesson, we’re going to determine whether or not a set of brackets are balanced or not by making use of the stack data structure that we defined in the previous lesson.
Let’s first understand what a balanced set of brackets looks like.
A balanced set of brackets is one where the number and type of opening and closing brackets match and that is also properly nested within the string of brackets.
Examples of Balanced Brackets #
- { }
- { } { }
- ( ( { [ ] } ) )
Examples of Unbalanced Brackets #
- ( ( )
- { { { ) } ]
- [ ] [ ] ] ]
Algorithm #
Check out the slides below to have a look at the approach we’ll use to solve this problem:
As shown above, our algorithm is as follows:
- We iterate through the characters of the string.
- If we get an opening bracket, push it onto the stack.
- If we encounter a closing bracket, pop off an element from the stack and match it with the closing bracket. If it is an opening bracket and of the same type as the closing bracket, we conclude it is a successful match and move on. If it’s not, we will conclude that the set of brackets is not balanced.
- The stack will be empty at the end of iteration for a balanced example of brackets while we’ll be left with some elements in the stack for an unbalanced example.
No comments:
Post a Comment