# Problem Solving with Algorithms and Data Structures using Java: The Interactive Edition

## Section3.7Balanced 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 Java square brackets, [ and ], are used for array lists; curly braces, { and }, are used for delimiting code blocks and array initializations; and parentheses, ( and ), are used for arithmetic expressions. 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 basic parentheses checker from the previous section can, with a few changes, 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.
The Java program to implement this is shown in Listing 3.7.1. The only change appears in lines 22–23 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 balance checker returns false immediately.
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 symbol that must be matched in a balanced order. There are a number of other important uses for stacks in computer science. We will continue to explore them in the next sections.