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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Proposition 12.11: Given a str<strong>in</strong>g X ofn characters <strong>and</strong> a str<strong>in</strong>g Y of m<br />

characters, we can f<strong>in</strong>d the longest common subsequence of X <strong>and</strong> Y <strong>in</strong> O(nm)<br />

time.<br />

Justification: Algorithm LCS computes L[n − 1,m − 1], the length of a<br />

longest common subsequence, <strong>in</strong> O(nm) time. Given the table of L[i, j] values,<br />

construct<strong>in</strong>g a longest common subsequence is straightforward. One method is to<br />

start from L[n, m] <strong>and</strong> work back through the table, reconstruct<strong>in</strong>g a longest<br />

common subsequence from back to front. At any position L[i, j], we can<br />

determ<strong>in</strong>e whether x i = y j . If this is true, then we can take x i as the next character<br />

of the subsequence (not<strong>in</strong>g that x i is before the previous character we found, if<br />

any), mov<strong>in</strong>g next to L[i − 1, j − 1]. If x i ≠ y j , then we can move to the larger of<br />

L[i, j − 1] <strong>and</strong> L[i −1,j]. (See Figure 12.13.) We stop when we reach a boundary<br />

cell (with i = − 1 or j = −1). This method constructs a longest common<br />

subsequence <strong>in</strong> O(n + m) additional time.<br />

Figure 12.13: Illustration of the algorithm for<br />

construct<strong>in</strong>g a longest common subsequence from the<br />

array L.<br />

12.6 Exercises<br />

For source code <strong>and</strong> help with exercises, please visit<br />

java.datastructures.net.<br />

782

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

Saved successfully!

Ooh no, something went wrong!