Docsity

Notes on Strings and Pattern Matching Algorithms - Data Structures | CS 357, Study notes of Data Structures and Algorithms

Partial preview of the text

Download Notes on Strings and Pattern Matching Algorithms - Data Structures | CS 357 and more Study notes Data Structures and Algorithms in PDF only on Docsity!

CS 357 Data Structures

Lecture 27

Fall 2004

Department of Computer Science

University of Alabama

Overview

Announcement

Pattern Matching

Tries

Pattern Matching

Outline and Reading

Strings (§11.1)

Pattern matching algorithms

• Brute-force algorithm (§11.2.1)

• Boyer-Moore algorithm (§11.2.2)

• Knuth-Morris-Pratt algorithm (§11.2.3)

Brute-Force Algorithm

The brute-force pattern

matching algorithm compares

the pattern P with the text T

for each possible shift of P

relative to T , until either

  • a match is found, or
  • all placements of the pattern have been tried

Brute-force pattern matching

runs in time O ( nm )

Example of worst case:

- T = **_aaa … ah

  • P_** = aaah - (^) may occur in images and DNA sequences - (^) unlikely in English text

Algorithm BruteForceMatch ( T, P )

Input text T of size n and pattern

P of size m

Output starting index of a

substring of T equal to P or − 1

if no such substring exists

for i ← 0 to n − m

{ test shift i of the pattern }

j ← 0

while j < m ∧ T [ i + j ] = P [ j ]

j ← j + 1

if j = m

return i {match at i }

else

break while loop {mismatch}

return -1 {no match anywhere}

Boyer-Moore Heuristics

The Boyer-Moore’s pattern matching algorithm is based on two

heuristics

Looking-glass heuristic: Compare P with a subsequence of T

moving backwards

Character-jump heuristic: When a mismatch occurs at T [ i ] = c

  • If P contains c , shift P to align the last occurrence of c in P with T [ i ]
  • Else, shift P to align P [0] with T [ i + 1]

Example

Case 1: j ≤ 1 + l

The Boyer-Moore Algorithm

Algorithm BoyerMooreMatch ( T, P, Σ) L ← lastOccurenceFunction ( P, Σ ) i ← m − 1 j ← m − 1 repeat if T [ i ] = P [ j ] if j = 0 return i { match at i } else i ← i − 1 j ← j − 1 else { character-jump } l ← L [ T [ i ]] i ← i + m – min( j , 1 + l ) j ← m − 1 until i > n − 1 return − 1 { no match }

Case 2: 1 + l ≤ j

Example