LU4 String Searching v1
LU4 String Searching v1
String Searching
Mrs. G. Priyanka, AP(Sl.Gr)/CSE
Mepco Schlenk Engineering College, Sivakasi
Brute-Force : String Searching
• It is the process of finding pattern in the larger text. Also
called as String Matching.
• pattern: a string of m characters to search for.
• text: a (longer) string of n characters to search in.
• problem: given a string of n characters called the text and a
string of m characters (m ≤ n) called the pattern, find a
substring of the text that matches the pattern.
• Example:
• Pattern: Hi
• Text: Hello, Good Morning. Hi, Nice meeting you
Brute-Force : String Searching (Contd.,)
• such that
ti = p0, ti+1=p1, ...,ti+j = pj , ... ,ti+m−1 = pm−1
• Solution: If match occur, return index i. Otherwise return -1.
Brute-Force : String Searching (Contd.,)
Pattern: a b a b a c a
Brute-Force : String Searching-Example (Contd.,)
Text: b a c b a b a b a b a c a
Pattern: a b a b a c a
Brute-Force : String Searching-Example (Contd.,)
Text: b a c b a b a b a b a c a
Pattern: a b a b a c a
Brute-Force : String Searching-Example (Contd.,)
Text: b a c b a b a b a b a c a
Pattern: a b a b a c a
Brute-Force : String Searching-Example (Contd.,)
Text: b a c b a b a b a b a c a
Pattern: a b a b a c a
Brute-Force : String Searching-Example (Contd.,)
Text: b a c b a b a b a b a c a
Pattern: a b a b a c a
Brute-Force : String Searching-Example (Contd.,)
Text: b a c b a b a b a b a c a
Pattern: a b a b a c a
Brute-Force : String Searching-Example (Contd.,)
Text: b a c b a b a b a b a c a
Pattern: a b a b a c a
Brute-Force : String Searching-Example (Contd.,)
Text: b a c b a b a b a b a c a
Pattern: a b a b a c a
Brute-Force : String Searching-Example (Contd.,)
Text: b a c b a b a b a b a c a
Pattern: a b a b a c a
Brute-Force : String Searching-Example (Contd.,)
Text: b a c b a b a b a b a c a
Pattern: a b a b a c a
Brute-Force : String Searching-Example (Contd.,)
Text: b a c b a b a b a b a c a
Pattern: a b a b a c a
Brute-Force : String Searching-Example (Contd.,)
Text: b a c b a b a c a b a c a
Pattern: a b a b a c a
Brute-Force : String Searching-Example (Contd.,)
Text: b a c b a b a c a b a c a
Pattern: a b a b a c a
Brute-Force : String Searching-Example (Contd.,)
Text:
Pattern:
Brute-Force : String Searching - Algorithm
Brute-Force : String Searching – Algorithm (Contd.,)
=
=
= m(n-m-0+1)
=m.(n-m+1)
Therefore, C(n) = O(nm)
It means that, it may have to make all m comparisons before shifting
the pattern, and this can happen for (n−m+1) possible starting
positions in the input text.
Exercises
• Pattern: 001011
Text: 10010101101001100101111010
• Pattern: happy
Text: It is never too late to have a happy childhood.