Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class rabin_karp{
- public static void main(String args[]){
- int d = 256;
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter the text");
- String text = sc.nextLine();
- System.out.println("Enter the pattern");
- String pattern = sc.nextLine();
- int tlen = text.length();
- int plen = pattern.length();
- int p =0;
- int t = 0;
- int h = 1;
- int q = 101;
- for(int i = 0; i < plen-1; i++){
- h = (h*d)%q;
- }
- for(int i = 0; i < plen; i++){
- p = (d*p + pattern.charAt(i))%q;
- t = (d*t + text.charAt(i))%q;
- }
- int j;
- for (int i = 0; i <= tlen ; i++)
- {
- if(p == t)
- {
- for (j = 0; j < plen; j++)
- {
- if (text.charAt(i+j) != pattern.charAt(j))
- break;
- }
- if (j == plen)
- System.out.println("Pattern found at index " + i);
- }
- if ( i < tlen-plen )
- {
- t = (d*(t - text.charAt(i)*h) + text.charAt(i+plen))%q;
- if (t < 0){
- t = (t + q);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment