|
| 1 | +/** |
| 2 | + * @author Prateek Kumar Oraon (https://github.com/prateekKrOraon) |
| 3 | + */ |
| 4 | +importjava.util.Scanner; |
| 5 | +importjava.lang.Math; |
| 6 | + |
| 7 | +//An implementation of Rabin-Karp string matching algorithm |
| 8 | +//Program will simply end if there is no match |
| 9 | +publicclassRabinKarp { |
| 10 | + |
| 11 | +publicstaticScannerscanner =null; |
| 12 | +publicfinalstaticintd =256; |
| 13 | + |
| 14 | +publicstaticvoidmain(String[]args){ |
| 15 | + |
| 16 | +scanner =newScanner(System.in); |
| 17 | +System.out.println("Enter String"); |
| 18 | +Stringtext =scanner.nextLine(); |
| 19 | +System.out.println("Enter pattern"); |
| 20 | +Stringpattern =scanner.nextLine(); |
| 21 | + |
| 22 | +intq =101; |
| 23 | +searchPat(text,pattern,q); |
| 24 | + |
| 25 | + } |
| 26 | + |
| 27 | +privatestaticvoidsearchPat(Stringtext,Stringpattern,intq) { |
| 28 | + |
| 29 | +intm =pattern.length(); |
| 30 | +intn =text.length(); |
| 31 | +intt =0; |
| 32 | +intp =0; |
| 33 | +inth =1; |
| 34 | +intj =0; |
| 35 | +inti =0; |
| 36 | + |
| 37 | +h = (int)Math.pow(d,m-1)%q; |
| 38 | + |
| 39 | +for(i =0 ;i<m;i++){ |
| 40 | +//hash value is calculated for each character and then added with the hash value of the next character for pattern |
| 41 | +// as well as the text for length equal to the length of pattern |
| 42 | +p = (d*p +pattern.charAt(i))%q; |
| 43 | +t = (d*t +text.charAt(i))%q; |
| 44 | + } |
| 45 | + |
| 46 | +for(i=0;i<=n-m;i++){ |
| 47 | + |
| 48 | +//if the calculated hash value of the pattern and text matches then |
| 49 | +//all the characters of the pattern is matched with the text of length equal to length of the pattern |
| 50 | +//if all matches then pattern exist in string |
| 51 | +//if not then the hash value of the first character of the text is subtracted and hash value of the next character after the end |
| 52 | +//of the evaluated characters is added |
| 53 | +if(p==t){ |
| 54 | + |
| 55 | +//if hash value matches then the individual characters are matched |
| 56 | +for(j=0;j<m;j++){ |
| 57 | + |
| 58 | +//if not matched then break out of the loop |
| 59 | +if(text.charAt(i+j) !=pattern.charAt(j)) |
| 60 | +break; |
| 61 | + } |
| 62 | + |
| 63 | +//if all characters are matched then pattern exist in the string |
| 64 | +if (j==m){ |
| 65 | +System.out.println("Pattern found at index " +i); |
| 66 | + } |
| 67 | + |
| 68 | + } |
| 69 | + |
| 70 | +//if i<n-m then hash value of the first character of the text is subtracted and hash value of the next character after the end |
| 71 | +//of the evaluated characters is added to get the hash value of the next window of characters in the text |
| 72 | +if (i <n-m ) |
| 73 | + { |
| 74 | +t = (d*(t -text.charAt(i)*h) +text.charAt(i+m))%q; |
| 75 | + |
| 76 | +//if hash value becomes less than zero than q is added to make it positive |
| 77 | +if (t <0) |
| 78 | +t = (t +q); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + } |
| 83 | + |
| 84 | +} |