String Matching: Using Finite Automata
String Matching: Using Finite Automata
String Matching: Using Finite Automata
1
Example (I)
4
3
input: a b a b b a b b a a
2
Example (II)
state a b
4
0 1 0 3
1 1 2
2 1 3
3 4 0
4 1 2
3
Example (III)
2 1 3
3 4 0
4 1 2
4
Example (IV)
2 1 3
a b a b b a b b a a
3 4 0
0
4 1 2
5
Example (V)
2 1 3
a b a b b a b b a a
3 4 0
0 1
4 1 2
6
Example (VI)
2 1 3
a b a b b a b b a a
3 4 0
0 1 2
4 1 2
7
Example (VII)
2 1 3
a b a b b a b b a a
3 4 0
0 1 2 1
4 1 2
8
Example (VIII)
2 1 3
a b a b b a b b a a
3 4 0
0 1 2 1 2
4 1 2
9
Example (IX)
2 1 3
a b a b b a b b a a
3 4 0
0 1 2 1 2 3
4 1 2
10
Example (X)
2 1 3
a b a b b a b b a a
3 4 0
0 1 2 1 2 3 4
4 1 2
11
Example (XI)
2 1 3
a b a b b a b b a a
3 4 0
0 1 2 1 2 3 4 2 3 4 1
4 1 2
12
Finite-Automaton-Matcher
Finite-Automaton-Matcher(T,,P)
1. n length(T)
2. q 0
3. for i 1 to n do
4. q (q,T[i])
5. if q = m then
6. si-m
7. return “Pattern occurs with shift” s
13
Computing the Transition Function:
The Idea!
m a n a m a m a p a t i p i t
m a m a
m a m a
m a m a
m a m a
m a m a
m a m a
m a m a
14
How to Compute the Transition Function?
Compute-Transition-Function(P, )
1. m length(P)
2. for q 0 to m do
3. for each character a do
4. k 1+min(m,q+1)
5. repeat
k k-1
6. until Pk is a suffix of Pqa
7. (q,a) k
15
Example
a b a a b a a a a
Compute-Transition-Function(P, )
1. m length(P) Text a b a a b a a a P7a
2. for q 0 to m do
3. for each character a do a b a a b a a a P8
4. k 1+min(m,q+1)
5. repeat
k k-1
6. until Pk is a suffix of Pqa
7. (q,a) k
8.
16
Example
Compute-Transition-Function(P, ) a b a a b a a a P8
1. m length(P)
2. for q 0 to m do a b a a b a a P7
3. for each character a do
4. k 1+min(m,q+1) a b a a b a P6
5. repeat
k k-1 a b a a b P5
6. until Pk is a suffix of Pqa
7. (q,a) k
8.
17
Running time of Compute Transition-Function