KEMBAR78
Naive string matching algorithm | PDF
Naïve String Matching Algorithm
Dr. Kiran K
Assistant Professor
Department of CSE
UVCE
Bengaluru, India.
Introduction
T [1 . . n] : Text of length n.
P [1 . . m] : Pattern of length m.
∑ : A Finite Alphabet consisting of characters from which the elements of
P and T are drawn.
Eg.: ∑ = {0, 1}
∑ = {a, b, . . . , z}
String-Matching Problem:
Find All Valid Shifts with which a given Pattern P occurs in a given Text T.
Strings of Characters
Introduction…
Shift (s): A Pattern P is said to occur with shift s in text T, if 0 ≤ s ≤ n – m and
T [s + 1 . . s + m] = P [1 . . m]. (T [s + j] = P [j] for 1 ≤ j ≤ m)
P occurs beginning at position s + 1 in text T.
• Valid Shift: P occurs with shift s in T.
• Invalid Shift: P does not occur in T.
String-matching algorithms generally perform some Preprocessing based on the pattern and
then finds all Valid Shifts (Matching).
Algorithm
Finds All Valid Shifts using a loop that checks the condition:
P [1 . . m] = T [s + 1 . . s + m] for each of the n – m + 1 possible values of s.
NAIVE-STRING-MATCHER (T, P)
n = T.length
l = P.length
For (s = 0 to n – m)
If (P [1 . . m] = T [s + 1 . . s + m])
Print “Pattern occurs with shift s”
Running Time:
Worst Case: Ө ((n – m + 1) m)
Best Case: Ө (n + m)
References:
• Thomas H Cormen. Charles E Leiserson, Ronald L Rivest, Clifford Stein,
Introduction to Algorithms, Third Edition, The MIT Press Cambridge,
Massachusetts London, England.

Naive string matching algorithm

  • 1.
    Naïve String MatchingAlgorithm Dr. Kiran K Assistant Professor Department of CSE UVCE Bengaluru, India.
  • 2.
    Introduction T [1 .. n] : Text of length n. P [1 . . m] : Pattern of length m. ∑ : A Finite Alphabet consisting of characters from which the elements of P and T are drawn. Eg.: ∑ = {0, 1} ∑ = {a, b, . . . , z} String-Matching Problem: Find All Valid Shifts with which a given Pattern P occurs in a given Text T. Strings of Characters
  • 3.
    Introduction… Shift (s): APattern P is said to occur with shift s in text T, if 0 ≤ s ≤ n – m and T [s + 1 . . s + m] = P [1 . . m]. (T [s + j] = P [j] for 1 ≤ j ≤ m) P occurs beginning at position s + 1 in text T. • Valid Shift: P occurs with shift s in T. • Invalid Shift: P does not occur in T. String-matching algorithms generally perform some Preprocessing based on the pattern and then finds all Valid Shifts (Matching).
  • 4.
    Algorithm Finds All ValidShifts using a loop that checks the condition: P [1 . . m] = T [s + 1 . . s + m] for each of the n – m + 1 possible values of s. NAIVE-STRING-MATCHER (T, P) n = T.length l = P.length For (s = 0 to n – m) If (P [1 . . m] = T [s + 1 . . s + m]) Print “Pattern occurs with shift s” Running Time: Worst Case: Ө ((n – m + 1) m) Best Case: Ө (n + m)
  • 5.
    References: • Thomas HCormen. Charles E Leiserson, Ronald L Rivest, Clifford Stein, Introduction to Algorithms, Third Edition, The MIT Press Cambridge, Massachusetts London, England.