MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / RabinKarp

Class RabinKarp

RabinKarp.java:2–68  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1import java.util.*;
2public class RabinKarp {
3
4 public static void main(String args[])
5 {
6 Scanner obj = new Scanner(System.in);
7 System.out.println("Enter input string");
8 String input=obj.nextLine();
9 System.out.println("Enter input string");
10 String pattern=obj.nextLine();
11 rabinKarp(input,pattern);
12
13
14 }
15 public static int rabinKarp(String str, String pattern)
16 {
17
18 // base
19 if(pattern.length()>str.length() || pattern.length()==0) return -1;
20
21
22 // rabin - karp
23
24 int alphabets=26;
25
26 int patternHashCode = HashFunction(pattern,alphabets);
27
28 int window = pattern.length();
29
30 int index=-1;
31
32 int substringHashCode = HashFunction(str.substring(0,window),alphabets);
33
34 for(int i=1;i<str.length()-window+1;i++)
35 {
36 int prev = str.charAt(i-1) * (int)Math.pow(alphabets,pattern.length()-1);
37
38 substringHashCode = (substringHashCode - prev)*alphabets + str.charAt(i+window-1);
39
40 if(substringHashCode==patternHashCode)
41 {
42 if(str.substring(i,i+window).equals(pattern))
43 {
44 System.out.println("found at index: "+ i);
45 }
46 }
47 }
48 return index;
49 }
50
51 public static int HashFunction(String inp, int alphabets)
52 {
53 int k=inp.length()-1;
54
55 int res=0;
56
57 for(int i=0;i<inp.length();i++)
58 {
59 int asc = inp.charAt(i);
60

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected