Section 3.7 Balanced Symbols - A General Case
The balanced parentheses problem shown above is a specific case of a more general situation that arises in many programming languages. The general problem of balancing and nesting different kinds of opening and closing symbols occurs frequently. For example, in Python square brackets,
[
and ]
, are used for lists; curly brackets, {
and }
, are used for dictionaries; and parenthesis, (
and )
, are used for tuples and arithmetic expressions. In C++, square brackets, [
and ]
, are used for arrays and vectors, brackets {
and }
separate possibly nested blocks of code, and operations are given inside of possibly nested parentheses (
and )
. It is possible to mix symbols as long as each maintains its own open and close relationship. Strings of symbols such as{ { ( [ ] [ ] ) } ( ) } [ [ { { ( ( ) ) } } ] ] [ ] [ ] [ ] ( ) { }
are properly balanced in that not only does each opening symbol have a corresponding closing symbol, but the types of symbols match as well.
Compare those with the following strings that are not balanced:
( [ ) ] ( ( ( ) ] ) ) [ { ( ) ]
The simple parentheses checker from the previous section can easily be extended to handle these new types of symbols. Recall that each opening symbol is simply pushed on the stack to wait for the matching closing symbol to appear later in the sequence. When a closing symbol does appear, the only difference is that we must check to be sure that it correctly matches the type of the opening symbol on top of the stack. If the two symbols do not match, the string is not balanced. Once again, if the entire string is processed and nothing is left on the stack, the string is correctly balanced.
Implementations of this are shown in Task 3.7.1.a. The key C++ feature appears in line 38 where we call a helper function,
matches
, to assist with symbol-matching. Each symbol that is removed from the stack must be checked to see that it matches the current closing symbol. If a mismatch occurs, the Boolean variable balanced
is set to false
.These two examples show that stacks are very important data structures for the processing of language constructs in computer science. Almost any notation you can think of has some type of nested symbols that must be matched in a balanced order. A number of other important uses for stacks exist in computer science. We will continue to explore them in the next sections.
Reading Questions Reading Question
1.
You have attempted of activities on this page.