Pattern Search using Rabin Karp
This program searches for pattern using Rabin Karp algorithm.
Problem Statement
Write a Java program to search "test" in "thisisateststringtest".
Source Code
| 1 | public class RabinKarpPatternSearch { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq Rabin Karp Pattern Search"); |
| 4 | String txt="thisisateststringtest", pat="test"; |
| 5 | int d=256,q=101; |
| 6 | int m=pat.length(), n=txt.length(); |
| 7 | int p=0,t=0,h=1; |
| 8 | for(int i=0;i<m-1;i++) h=(h*d)%q; |
| 9 | for(int i=0;i<m;i++){ |
| 10 | p=(d*p+pat.charAt(i))%q; |
| 11 | t=(d*t+txt.charAt(i))%q; |
| 12 | } |
| 13 | for(int i=0;i<=n-m;i++){ |
| 14 | if(p==t){ |
| 15 | if(txt.substring(i,i+m).equals(pat)) |
| 16 | System.out.println("Found at index "+i); |
| 17 | } |
| 18 | if(i<n-m){ |
| 19 | t=(d*(t-txt.charAt(i)*h)+txt.charAt(i+m))%q; |
| 20 | if(t<0) t+=q; |
| 21 | } |
| 22 | } |
| 23 | } |
| 24 | } |
Program Output
Eduinq Rabin Karp Pattern Search Found at index 7 Found at index 17
Explanation
A rolling hash value is computed for both the pattern and the text window, and whenever the hashes match, a direct substring comparison confirms the actual match, demonstrating the Rabin-Karp algorithm applied to pattern searching.