Professional Documents
Culture Documents
Abdul Rauf (021!21!0019) Assignment2
Abdul Rauf (021!21!0019) Assignment2
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:
positions = []
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
if pattern[i] == pattern[j]:
j += 1
lps[i] = j
return lps
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: