You are on page 1of 3

1.

Naive String Matching Algorithm:

DEFINATION: The Naive String Matching Algorithm, also known as the Brute-Force algorithm, is a
simple and straightforward method for finding occurrences of a pattern within a text. The algorithm
involves systematically checking all possible positions of the pattern in the text. At each position, the
algorithm compares characters of the pattern with the corresponding characters in the text. If a
mismatch is found, it shifts to the next position in the text and repeats the process until a match is
found or the end of the text is reached.

CODE:

def naive_string_match(text, pattern):


n = len(text)
m = len(pattern)

positions = []

for i in range(n - m + 1):


j=0
while j < m and text[i + j] == pattern[j]:
j += 1

if j == m:
positions.append(i)

return positions

text = "ABABDABACDABABCABAB"
pattern = "ABABC"
result = naive_string_match(text, pattern)
print(f"Pattern found at positions: {result}")

OUTPUT:
2. Knuth-Morris-Pratt (KMP) Algorithm:

DEFINATION: The Knuth-Morris-Pratt (KMP) Algorithm is an efficient string matching algorithm that
improves upon the Naive algorithm by utilizing information from previous character comparisons to
avoid unnecessary backtracking. The key idea is to precompute a partial match table, often referred
to as the "longest proper prefix which is also a suffix" table (LPS table). This table helps the algorithm
skip portions of the text that cannot lead to a match based on the information from previous
comparisons.

CODE:

def kmp_preprocess(pattern):
m = len(pattern)
lps = [0] * m
j=0

for i in range(1, m):


while j > 0 and pattern[i] != pattern[j]:
j = lps[j - 1]

if pattern[i] == pattern[j]:
j += 1

lps[i] = j

return lps

def kmp_string_match(text, pattern):


n = len(text)
m = len(pattern)
lps = kmp_preprocess(pattern)

positions = []
i=j=0

while i < n:
if pattern[j] == text[i]:
i += 1
j += 1

if j == m:
positions.append(i - j)
j = lps[j - 1]
else:
if j != 0:
j = lps[j - 1]
else:
i += 1

return positions

# Example usage:
text = "ABABDABACDABABCABAB"
pattern = "ABABC"
result = kmp_string_match(text, pattern)
print(f"Pattern found at positions: {result}")
OUTPUT:

You might also like