Skip to content

Commit 8374edc

Browse files
committed
Added String Matching Robin Carp Algorithm in Java
1 parent d53d6fa commit 8374edc

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

RobinCarp/Java/RabinKarp.java

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
* Author:- Prarik Kayastha
3+
* Email-id:- [email protected]
4+
* Program Name:- Rabin-Karp Algorithm
5+
* Description:- This algorithm uses to find pattern in given string.
6+
* Time-Complexity:- O(mn)
7+
* */
8+
9+
import java.util.Scanner;
10+
11+
public class RabinKarp {
12+
13+
static final long prime = 101;
14+
public static String searchSubstring(String str,int n,String sub,int m)
15+
{
16+
long key= getSubKey(sub, m);
17+
long oldHash = getSubKey(str.substring(0, m), m);
18+
if(key==oldHash && equal(str, sub, 0))
19+
return "Yes";
20+
for(int i=m;i<n;i++)
21+
{
22+
oldHash = getNewHash(str, i-m, i, oldHash, m);
23+
if(key==oldHash && equal(str, sub, i-m+1))
24+
return "Yes";
25+
}
26+
return "No";
27+
}
28+
public static long getNewHash(String str,int oldIndex,int newIndex,long oldHash,int m)//get newhash in constant time
29+
{
30+
long newHash=((oldHash-str.charAt(oldIndex)+96)/prime)+((str.charAt(newIndex)-96)*(long)Math.pow(prime, m-1));
31+
return newHash;
32+
}
33+
public static long getSubKey(String sub,int m)//hashing function
34+
{
35+
long key=0;
36+
for(int i=0;i<m;i++)
37+
{
38+
key += (sub.charAt(i)-96)*(long)Math.pow(prime, i);
39+
}
40+
return key;
41+
}
42+
public static boolean equal(String str,String sub,int index)//to check two string are equal or not
43+
{
44+
for(int i=0;i<sub.length();i++)
45+
if(str.charAt(index+i)!=sub.charAt(i))
46+
return false;
47+
return true;
48+
}
49+
public static void main(String[] args) {
50+
// TODO Auto-generated method stub
51+
Scanner sc = new Scanner(System.in);
52+
String str = sc.nextLine();
53+
String sub = sc.nextLine();
54+
int n = str.length();
55+
int m = sub.length();
56+
System.out.println(searchSubstring(str,n,sub,m));
57+
sc.close();
58+
}
59+
60+
}

0 commit comments

Comments
 (0)