File tree 1 file changed +69
-0
lines changed
1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include <stdio.h>
2
+ #include <string.h>
3
+ void computeLPSArray (char * pat , int M , int * lps );
4
+ void KMPSearch (char * pat , char * txt )
5
+ {
6
+ int M = strlen (pat );
7
+ int N = strlen (txt );
8
+ int lps [M ];
9
+ computeLPSArray (pat , M , lps );
10
+ int i = 0 ;
11
+ int j = 0 ;
12
+ while ((N - i ) >= (M - j ))
13
+ {
14
+ if (pat [j ] == txt [i ])
15
+ {
16
+ j ++ ;
17
+ i ++ ;
18
+ }
19
+ if (j == M )
20
+ {
21
+ printf ("%d " , i - j );
22
+ j = lps [j - 1 ];
23
+ }
24
+ else if (i < N && pat [j ] != txt [i ])
25
+ {
26
+ if (j != 0 )
27
+ j = lps [j - 1 ];
28
+ else
29
+ i = i + 1 ;
30
+ }
31
+ }
32
+ printf ("\n" );
33
+ for (int i = 0 ;i < M ;i ++ )
34
+ printf ("%d " ,lps [i ]);
35
+ }
36
+ void computeLPSArray (char * pat , int M , int * lps )
37
+ {
38
+ int len = 0 ;
39
+ lps [0 ] = 0 ;
40
+ int i = 1 ;
41
+ while (i < M )
42
+ {
43
+ if (pat [i ] == pat [len ])
44
+ {
45
+ len ++ ;
46
+ lps [i ] = len ;
47
+ i ++ ;
48
+ }
49
+ else
50
+ {
51
+ if (len != 0 )
52
+ len = lps [len - 1 ];
53
+ else
54
+ {
55
+ lps [i ] = 0 ;
56
+ i ++ ;
57
+ }
58
+ }
59
+ }
60
+ }
61
+ int main ()
62
+ {
63
+ char txt [50 ];
64
+ char pat [50 ];
65
+ scanf ("%[^\n]s" ,txt );
66
+ scanf ("%s" ,pat );
67
+ KMPSearch (pat , txt );
68
+ return 0 ;
69
+ }
You can’t perform that action at this time.
0 commit comments