File tree 1 file changed +58
-0
lines changed
src/main/java/com/packt/datastructuresandalg/lesson5/goodsuffixrule
1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .packt .datastructuresandalg .lesson5 .goodsuffixrule ;
2
+
3
+ import java .util .ArrayList ;
4
+ import java .util .List ;
5
+
6
+ public class GoodSuffixRule {
7
+ public List <Integer > match (String P , String T ) {
8
+ int n = T .length ();
9
+ int m = P .length ();
10
+ int i = m , j = m + 1 ;
11
+ int [] f = new int [m + 1 ];
12
+ int [] s = new int [m + 1 ];
13
+ f [i ] = j ;
14
+ while (i > 0 ) {
15
+ while (j <= m && P .charAt (i - 1 ) != P .charAt (j - 1 )) {
16
+ if (s [j ] == 0 )
17
+ s [j ] = j - i ;
18
+ j = f [j ];
19
+ }
20
+ i --; j --;
21
+ f [i ] = j ;
22
+ }
23
+
24
+ j = f [0 ];
25
+ for (i = 0 ; i <= m ; i ++) {
26
+ if (s [i ] == 0 )
27
+ s [i ] = j ;
28
+ if (i == j )
29
+ j = f [j ];
30
+ }
31
+
32
+ List <Integer > shifts = new ArrayList <>();
33
+ int skip ;
34
+ for (i = 0 ; i < n - m + 1 ; i += skip ) {
35
+ boolean hasMatch = true ;
36
+ skip = 0 ;
37
+ for (j = m - 1 ; j >= 0 ; j --) {
38
+ if (P .charAt (j ) != T .charAt (i + j )) {
39
+ skip = s [j + 1 ];
40
+ hasMatch = false ;
41
+ break ;
42
+ }
43
+ }
44
+ if (hasMatch ) {
45
+ shifts .add (i );
46
+ skip = s [0 ];
47
+ }
48
+ }
49
+ return shifts ;
50
+ }
51
+
52
+ public static void main (String [] args ) {
53
+ GoodSuffixRule gsr = new GoodSuffixRule ();
54
+ List <Integer > matches = gsr .match ("rabrabracad" , "abacadabrabracabracadabrabrabracad" );
55
+ for (Integer i : matches )
56
+ System .out .println (i );
57
+ }
58
+ }
You can’t perform that action at this time.
0 commit comments