-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathRKPattern.java
More file actions
53 lines (45 loc) · 1.75 KB
/
RKPattern.java
File metadata and controls
53 lines (45 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class RKPattern {
public static void main(String[] args) {
/*
* 1. Slide the Pattern One By One
* 2. Do the Better Hash
* 3. If Hash are same then compare the characters
* 4. Repeat the 1st Step Again till string exhaust
*/
String str = "AXAYABCDAXABZZAWABAD";
String pattern = "AB";
int n = str.length();
int p = pattern.length();
int d = pattern.length();
int q = 13; // Prime No / Large Prime No (If Hash is coming Negative)
int stringHash = 0;
int patternHash = 0;
// Compute the Pattern Hash First
for (int i = 0; i < p; i++) {
patternHash = (patternHash * d + (pattern.charAt(i))) % q;
stringHash = (stringHash * d + (str.charAt(i))) % q;
}
for (int i = 0; i <= n - p; i++) {
if (patternHash == stringHash) {
// compare the pattern with string values one by one
int j;
for (j = 0; j < p; j++) {
if (pattern.charAt(j) != str.charAt(i + j)) {
break;
}
} // j loop ends (Pattern loop ends)
if (j == p) {
System.out.println("Pattern Match " + i);
}
}
// recompute str Hash only
if (i < n - p) {
stringHash = stringHash - (str.charAt(i) *d); // Remove the Old char Hash of Slide
stringHash = ((stringHash * d + str.charAt(i + p))) % q; // add the New Char hash of Slide
if (stringHash < 0) {
stringHash = stringHash + q;
}
}
}
}
}