Java Program for Rabin-Karp Algorithm for Pattern Searching
Input: txt = "THIS IS A TEST TEXT" pat = "TEST" Output: Pattern found at index 10 Input: txt = "AABAACAADAABAABA" pat = "AABA" Output: Pattern found at index 0 Pattern found at index 9 Pattern found at index 12
The Naive String Matching algorithm slides the pattern one by one. After each slide, it one by one checks characters at the current shift and if all characters match then prints the match.
Like the Naive Algorithm, Rabin-Karp algorithm also slides the pattern one by one. But unlike the Naive algorithm, Rabin Karp algorithm matches the hash value of the pattern with the hash value of current substring of text, and if the hash values match then only it starts matching individual characters. So Rabin Karp algorithm needs to calculate hash values for following strings.
1) Pattern itself.
2) All the substrings of text of length m.
Pattern found at index 0 Pattern found at index 10
Time Complexity: O(M+N)
Space Complexity: O(1)
Please refer complete article on Rabin-Karp Algorithm for Pattern Searching for more details!
Please Login to comment...