8000 KarpRabin code · Ismail0290/DSA-Bootcamp-Java@5c45a42 · GitHub
[go: up one dir, main page]

Skip to content

Commit 5c45a42

Browse files
KarpRabin code
1 parent 380f8b0 commit 5c45a42

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
public class KarpRabin {
2+
private final int PRIME = 101;
3+
4+
private double calculateHash(String str) {
5+
double hash = 0;
6+
for(int i=0; i < str.length(); i++) {
7+
hash += str.charAt(i) * Math.pow(PRIME, i);
8+
}
9+
return hash;
10+
}
11+
12+
private double updateHash(double prevHash, char oldChar, char newChar, int patternLength) {
13+
double newHash = (prevHash - oldChar) / PRIME;
14+
newHash = newHash + newChar * Math.pow(PRIME, patternLength - 1);
15+
return newHash;
16+
}
17+
18+
public void search(String text, String pattern) {
19+
int patternLength = pattern.length();
20+
double patternHash = calculateHash(pattern);
21+
double textHash = calculateHash(text.substring(0, patternLength));
22+
23+
for(int i=0; i<= text.length() - patternLength; i++) {
24+
if(textHash == patternHash) {
25+
if(text.substring(i, i+patternLength).equals(pattern)) {
26+
System.out.println("Pattern found at index " + i);
27+
}
28+
}
29+
30+
if (i < text.length() - patternLength) {
31+
textHash = updateHash(textHash, text.charAt(i), text.charAt(i + patternLength), patternLength);
32+
}
33+
}
34+
}
35+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
class Main {
2+
public static void main(String[] args) {
3+
KarpRabin algo = new KarpRabin();
4+
algo.search("ApoorvKunalRahul", "Kunal");
5+
}
6+
}

0 commit comments

Comments
 (0)
0