![]() |
VOOZH | about |
There are so many pattern searching algorithms for the string. KMP algorithm, Z algorithm Rabin Karp algorithm, etc these algorithms are the optimization of Naive Pattern searching Algorithm.
Naive Pattern Searching Algorithm:
Input : "AABACACAACAC" Pattern : "CAC" Output : [4,9] AABACACAACAC
Implementation:
Pattern is found at the indices : 4 , 9 ,
Output explanation:
The above algorithm for pattern searching is the basic algorithm the worst as the average time complexity of this algorithm is O(n×m) where n is the pattern and m is the given string.
How can we reduce the complexity of this algorithm?
It is possible with the help of rolling hash. Rabin Karp algorithm is one of the optimized algorithms of the naive algorithm that performs searching by rolling over the string and search the pattern.
Illustration:
Input: txt[] = "THIS IS A TEST TEXT" pat[] = "TEST" Output: Pattern found at index 10 Input: txt[] = "AABAACAADAAB" pat[] = "AABA" Output: Pattern found at index 0 Pattern found at index 9 Pattern found at index 12
Procedure:
Implementation:
Simple Rolling algorithm assuming the pattern of length 2
0 9 12