-
Notifications
You must be signed in to change notification settings - Fork 62
/
RabinKarp.java
42 lines (37 loc) · 950 Bytes
/
RabinKarp.java
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
package algorithm.string;
/**
* @author roseduan[roseduan520@gmail.com]
* @time 2019/7/5 21:17
* @description RK算法,使用哈希算法提升字符串匹配效率
*/
public class RabinKarp {
public static int rk(String main, String ptn) {
int n = main.length();
int m = ptn.length();
if (n == 0 || m == 0 || m > n){
return -1;
}
int p = hash(ptn);
for (int i = 0; i <= n - m; i++) {
String sub = main.substring(i, i + m);
int q = hash(sub);
if (p == q && sub.equals(ptn)) {
return i;
}
}
return -1;
}
/**
* 哈希函数
*/
private static int hash(String key) {
char[] value = key.toCharArray();
int h = 0;
if (value.length > 0) {
for (char c : value) {
h = 31 * h + c;
}
}
return h;
}
}