0% found this document useful (0 votes)
21 views13 pages

Se - 31

Uploaded by

22r11a6259
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views13 pages

Se - 31

Uploaded by

22r11a6259
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 13

18CS22707S

Analysis and Design of Algorithms

STRING MATCHING
Session-31
String Matching
• Text-editing programs frequently need to find
all occurrences of a pattern in the text.
• Given a text is an array T[1..n] of length n and
a pattern P[1..m] of length m<=n.
• We say that pattern P occurs with shift s in
text T if 0≤s≤ n-m and T[s+1..s+m] = P[1..m].
• If P occurs with shift s in T , then we call s a
valid shift; otherwise, we call s an invalid shift.
String Matching
• The string-matching problem is the problem
of finding all valid shifts with which a given
pattern P occurs in a given text T .
• Example: T = ababcabdabcaabc and P = abc,
the occurrences are:
– first occurrence starts at T[3]
– second occurrence starts at T[9]
– third occurrence starts at T[13]
• Applications:
– Searching keywords in a file
– Searching engines (like Google and
Openfind)
– Database searching (GenBank)
The naive string-matching algorithm

The naive 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.
Algorithm
Running Time
At every step, after ‘m’ comparisons a
match/mismatch will be found.

These ‘m’ comparisons will be done for (n-m)


characters in T.

Thus, the running time obtained is (n-m)m + m.


Example

T: a b c a b d a a b c d e

P: a b d
Example ( Step – 1 )

T: a b c a b d a a b c d e

P: a b d

Mismatch after 3 Comparisons


Example ( Step – 2 )

T: a b c a b d a a b c d e

a b d
P:

Mismatch after 1 Comparison


Example ( Step – 3 )

T: a b c a b d a a b c d e

a b d
P:

Mismatch after 1 Comparison


Example ( Step – 4 )

T: a b c a b d a a b c d e

a b d
P:

Match found after 3 Comparisons

Thus, after 8 comparisons the substring P is found


in T.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy