1+ /**
2+ * @author Prateek Kumar Oraon (https://github.com/prateekKrOraon)
3+ */
4+ import java .util .Scanner ;
5+
6+ //An implementaion of string matching using finite automata
7+ public class StringMatchFiniteAutomata {
8+
9+ public static final int CHARS = 256 ;
10+ public static int [][] FA ;
11+ public static Scanner scanner = null ;
12+
13+ public static void main (String [] args ){
14+
15+ scanner = new Scanner (System .in );
16+ System .out .println ("Enter String" );
17+ String text = scanner .nextLine ();
18+ System .out .println ("Enter pattern" );
19+ String pat = scanner .nextLine ();
20+
21+ searchPat (text , pat );
22+
23+ scanner .close ();
24+
25+ }
26+
27+ public static void searchPat (String text , String pat ){
28+
29+ int m = pat .length ();
30+ int n = text .length ();
31+
32+ FA = new int [m +1 ][CHARS ];
33+
34+ computeFA (pat , m ,FA );
35+
36+ int state = 0 ;
37+ for (int i =0 ;i <n ;i ++){
38+ state = FA [state ][text .charAt (i )];
39+
40+ if (state == m ){
41+ System .out .println ("Pattern found at index " + (i -m +1 ));
42+ }
43+ }
44+
45+ }
46+
47+ //Computes finite automata for the partern
48+ public static void computeFA (String pat , int m , int [][] FA ){
49+
50+ for (int state = 0 ; state <= m ; ++state ){
51+ for (int x =0 ; x < CHARS ; ++x ){
52+ FA [state ][x ] = getNextState (pat , m , state , x );
53+ }
54+ }
55+
56+ }
57+
58+ public static int getNextState (String pat , int m , int state , int x ){
59+
60+ //if current state is less than length of pattern
61+ //and input character of pattern matches the character in the alphabet
62+ //then automata goes to next state
63+ if (state < m && x ==pat .charAt (state )){
64+ return state +1 ;
65+ }
66+
67+ for (int ns = state ; ns >0 ; ns --){
68+
69+ if (pat .charAt (ns -1 ) == x ){
70+
71+ for (int i =0 ; i <ns -1 ; i ++){
72+
73+ if (pat .charAt (i ) != pat .charAt (state -ns +i +1 )){
74+ break ;
75+ }
76+
77+ if (i == ns -1 ){
78+ return ns ;
79+ }
80+
81+ }
82+
83+ }
84+
85+ }
86+
87+ return 0 ;
88+
89+ }
90+
91+ }
0 commit comments