Daa Exp 09
Daa Exp 09
Experiment 9
Aim To understand and implement String Matching Algorithm
Calculate Initial Hashes: Calculate the hash values for the pattern and
the first substring of the text with the same length as the pattern.
Search: Iterate through the text, comparing the hash value of the current
substring with the hash value of the pattern. If they match, perform a
character-by-character comparison to confirm the match.
Update Hashes: If the hash values don't match, update the hash value of
the current substring using a rolling hash function. This function
efficiently updates the hash value by removing the contribution of the
first character and adding the contribution of the next character.
Repeat: Continue the process until all substrings of the text have been
checked.
while (i < N) {
if (pattern.charAt(j) ==
text.charAt(i)) {
i++;
j++;
}
if (j == M) {
System.out.println("Pattern found
at index " + (i - j));
j = lps[j - 1];
} else if (i < N && pattern.charAt(j)
!= text.charAt(i)) {
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
}
//Karp-Rabin
package DAA;
public class KarpRabin {
private final int PRIME = 101;
if (i < text.length() -
patternLength) {
textHash = updateHash(textHash,
text.charAt(i), text.charAt(i + patternLength),
patternLength);
}
}
}
Justification of KMP :
the complexity The time complexity of the Knuth-Morris-Pratt (KMP) algorithm for
calculated pattern searching in a text of length n using a pattern of length m is
O(n+m).
The searching step iterates through the text once, comparing each
character to the corresponding character in the pattern.
In the worst case, each character of the text may be compared against all
characters of the pattern.
However, due to the lps array, we can avoid unnecessary comparisons
by skipping ahead in the pattern whenever a mismatch occurs.
Thus, the searching step also takes O(n+m) time.
Karp-Rabin:
Update Hashes:
When moving the window along the text, updating the hash value can
be done in constant time with a rolling hash function.