23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The follow<strong>in</strong>g examples further illustrate this concept:<br />

• Correct: ( )(( )){([( )])}<br />

• Correct: ((( )(( )){([( )])}))<br />

• Incorrect: )(( )){([( )])}<br />

• Incorrect: ({[])}<br />

• Incorrect: (.<br />

We leave the precise def<strong>in</strong>ition of match<strong>in</strong>g of group<strong>in</strong>g symbols to Exercise R-5.5.<br />

An Algorithm for Parentheses Match<strong>in</strong>g<br />

An important problem <strong>in</strong> process<strong>in</strong>g arithmetic expressions is to make sure their<br />

group<strong>in</strong>g symbols match up correctly. We can use a stack S to perform the<br />

match<strong>in</strong>g of group<strong>in</strong>g symbols <strong>in</strong> an arithmetic expression with a s<strong>in</strong>gle left-toright<br />

scan. The algorithm tests that left <strong>and</strong> right symbols match up <strong>and</strong> also that<br />

the left <strong>and</strong> right symbols are both of the same type.<br />

Suppose we are given a sequence X = x 0 x 1 x 2 …x n−1 , where each x i is a token that<br />

can be a group<strong>in</strong>g symbol, a variable name, an arithmetic operator, or a number.<br />

The basic idea beh<strong>in</strong>d check<strong>in</strong>g that the group<strong>in</strong>g symbols <strong>in</strong> S match correctly, is<br />

to process the tokens <strong>in</strong> X <strong>in</strong> order. Each time we encounter an open<strong>in</strong>g symbol,<br />

we push that symbol onto S, <strong>and</strong> each time we encounter a clos<strong>in</strong>g symbol, we<br />

pop the top symbol from the stack S (assum<strong>in</strong>g S is not empty) <strong>and</strong> we check that<br />

these two symbols are of the same type. If the stack is empty after we have<br />

processed the whole sequence, then the symbols <strong>in</strong> X match. Assum<strong>in</strong>g that the<br />

push <strong>and</strong> pop operations are implemented to run <strong>in</strong> constant time, this algorithm<br />

runs <strong>in</strong> O(n), that is l<strong>in</strong>ear, time. We give a pseudo-code description of this<br />

algorithm <strong>in</strong> Code Fragment 5.10.<br />

Code Fragment 5.10: Algorithm for match<strong>in</strong>g<br />

group<strong>in</strong>g symbols <strong>in</strong> an arithmetic expression.<br />

280

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!