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.

Turn<strong>in</strong>g this def<strong>in</strong>ition of L[i, j] <strong>in</strong>to an algorithm is actually quite<br />

straightforward. We <strong>in</strong>itialize an (n+ 1) × (m + 1) array, L, for the boundary cases<br />

when i = 0 or j = 0. Namely, we <strong>in</strong>itialize L[i, − 1] = 0 for i = −1,0,1,…, n − 1 <strong>and</strong><br />

L[− 1, j] = 0 for j = −1,0,1,…, m − 1. (This is a slight abuse of notation, s<strong>in</strong>ce <strong>in</strong><br />

reality, we would have to <strong>in</strong>dex the rows <strong>and</strong> columns of L start<strong>in</strong>g with 0.) Then,<br />

we iteratively build up values <strong>in</strong> L until we have L[n − 1, m − 1], the length of a<br />

longest common subsequence of X <strong>and</strong> Y. We give a pseudo-code description of<br />

how this approach results <strong>in</strong> a dynamic programm<strong>in</strong>g solution to the longest<br />

common subsequence (LCS) problem <strong>in</strong> Code Fragment 12.9.<br />

Code Fragment 12.9: Dynamic programm<strong>in</strong>g<br />

algorithm for the LCS problem.<br />

Performance<br />

The runn<strong>in</strong>g time of the algorithm of Code Fragment 12.9 is easy to analyze, for it<br />

is dom<strong>in</strong>ated by two nested for loops, with the outer one iterat<strong>in</strong>g n times <strong>and</strong> the<br />

<strong>in</strong>ner one iterat<strong>in</strong>g m times. S<strong>in</strong>ce the if-statement <strong>and</strong> assignment <strong>in</strong>side the loop<br />

each requires O(1) primitive operations, this algorithm runs <strong>in</strong> O(nm) time. Thus,<br />

the dynamic programm<strong>in</strong>g technique can be applied to the longest common<br />

subsequence problem to improve significantly over the exponential-time bruteforce<br />

solution to the LCS problem.<br />

Algorithm LCS (Code Fragment 12.9) computes the length of the longest<br />

common subsequence (stored <strong>in</strong> L[n − 1,m − 1]), but not the subsequence itself.<br />

As shown <strong>in</strong> the follow<strong>in</strong>g proposition, a simple postprocess<strong>in</strong>g step can extract<br />

the longest common subsequence from the array L returned by algorithm.<br />

781

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

Saved successfully!

Ooh no, something went wrong!