-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoyerMoore.java
More file actions
59 lines (54 loc) · 1.58 KB
/
BoyerMoore.java
File metadata and controls
59 lines (54 loc) · 1.58 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
54
55
56
57
58
59
import java.util.Random;;
public class BoyerMoore{
private String pat;
private int[] right;
public BoyerMoore(String pat){
this.pat=pat;
int M=pat.length();
int R=256;
right=new int[R];
for (int c=0;c<R;c++){
right[c]=-1;
}
for (int j=0;j<M;j++){
right[pat.charAt(j)]=j;
}
}
public int search(String txt){
int N=txt.length();
int M=pat.length();
int skip;
for (int i=0;i<=N-M;i+=skip){
skip=0;
for (int j=M-1;j>=0;j--){
if (pat.charAt(j)!=txt.charAt(i+j)){
skip=j-right[txt.charAt(i+j)];
if (skip<1) skip=1;
break;
}
}
if (skip==0) return i;
}
return N;
}
public static void main(String[] args){
Random r = new Random();
int V=100;
//int L=7;
String[] str={"a","b","c","d","e","f","g","h","i","j","k",
"l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
String string="";
int j=50+r.nextInt(20);
String pat="";
for (int i=0;i<V;i++){
String ss=str[r.nextInt(26)];
string+=ss;
if (i>j &&i<j+5){pat+=ss;}
}
BoyerMoore bm=new BoyerMoore(pat);
System.out.println(string);
System.out.println(pat);
System.out.println(bm.search(string));
System.out.println(j+1);
}
}