
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
622
|
Chapter 11: Data Structures and Algorithms
This code produces the following output:
Balance {}: 268
Balance {}: 268
where a -1 means that the items are balanced and a number greater than -1 indicates
the character position that contains the unbalanced character.
Discussion
Determining whether characters have a matching character is actually quite easy
when a
Stack<T> object is used. A stack works on a FILO principle. The first item
added to a stack is always the last one to be removed; conversely, the last item added
to a stack is always the first removed.
To see how the stack is used in matching characters, let’s see how you’d use it to
handle the following equation:
((a + (b)) + c) * d
The algorithm works like this: you iterate through all characters in the equation,
then any time you come upon a left or right parenthesis, you push or pop an item
from the stack. If you see a left parenthesis, you know to push it onto the stack. If
you see a right parenthesis, you know to pop a left parenthesis from the stack. In
fact, the left parenthesis that was popped off the stack is the matching left parenthe-
sis to the current right parenthesis. If all parentheses are balanced, the stack will be
empty after iterating through all characters in the equation. If the stack is not empty,
the top