Naive string matching algorithm
Naive string matching algorithm
How It Works
Let:
T be the text of length n
P be the pattern of length m
Example
Text (T): "AABAACAADAABAABA" (length=16)
Pattern (P): "AABA" (length=4)
Step-by-Step Matching
Let's find all positions where "AABA" appears in the text:
1. Check T[0:4] = "AABA" → ✅ Match at index 0
2. T[1:5] = "ABAA" → ❌ No match
3. T[2:6] = "BAAC" → ❌ No match
4. T[3:7] = "AACA" → ❌ No match
5. T[4:8] = "ACAA" → ❌ No match
6. T[5:9] = "CAAD" → ❌ No match
7. T[6:10] = "AADA" → ❌ No match
8. T[7:11] = "ADAA" → ❌ No match
9. T[8:12] = "DAAB" → ❌ No match
10. T[9:13] = "AABA" → ✅ Match at index 9
11. T[10:14] = "ABAA" → ❌ No match
12. T[11:15] = "BAAB" → ❌ No match
13. T[12:16] = "AABA" → ✅ Match at index 12
Steps:
1. Start from the beginning of the text.
2. For each position i from 0 to n - m:
o Compare the substring T [i…i+m-1] with P.
o If all characters match, record the position i as a match.
3. Repeat until the end of the text is reached.
n= length of text
m=length of pattern