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.

eg<strong>in</strong>n<strong>in</strong>g of P), we simply <strong>in</strong>crement the <strong>in</strong>dex for T (<strong>and</strong> keep the <strong>in</strong>dex variable<br />

for P at its beg<strong>in</strong>n<strong>in</strong>g). We repeat this process until we f<strong>in</strong>d a match of P <strong>in</strong> T or<br />

the <strong>in</strong>dex for T reaches n, the length of T (<strong>in</strong>dicat<strong>in</strong>g that we did not f<strong>in</strong>d the<br />

pattern P<strong>in</strong>T).<br />

Code Fragment 12.4: The KMP pattern match<strong>in</strong>g<br />

algorithm.<br />

The ma<strong>in</strong> part of the KMP algorithm is the while loop, which performs a<br />

comparison between a character <strong>in</strong> T <strong>and</strong> a character <strong>in</strong> P each iteration.<br />

Depend<strong>in</strong>g upon the outcome of this comparison, the algorithm either moves on<br />

to the next characters <strong>in</strong> T <strong>and</strong> P, consults the failure function for a new c<strong>and</strong>idate<br />

character <strong>in</strong> P, or starts over with the next <strong>in</strong>dex <strong>in</strong> T. The correctness of this<br />

algorithm follows from the def<strong>in</strong>ition of the failure function. Any comparisons<br />

that are skipped are actually unnecessary, for the failure function guarantees that<br />

all the ignored comparisons are redundant—they would <strong>in</strong>volve compar<strong>in</strong>g the<br />

same match<strong>in</strong>g characters over aga<strong>in</strong>.<br />

Figure 12.5: An illustration of the KMP pattern<br />

match<strong>in</strong>g algorithm. The failure function f for this<br />

pattern is given <strong>in</strong> Example 12.4. The algorithm<br />

performs 19 character comparisons, which are<br />

<strong>in</strong>dicated with numerical labels.<br />

758

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

Saved successfully!

Ooh no, something went wrong!