File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #include < bits/stdc++.h>
2+
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+
9+ int lps[M];
10+ computeLPSArray (pat, M, lps);
11+
12+ int i = 0 ;
13+ int j = 0 ;
14+ while (i < N) {
15+ if (pat[j] == txt[i]) {
16+ j++;
17+ i++;
18+ }
19+
20+ if (j == M) {
21+ printf (" Found pattern at index %d " , i - j);
22+ j = lps[j - 1 ];
23+ }
24+
25+
26+ else if (i < N && pat[j] != txt[i]) {
27+
28+ if (j != 0 )
29+ j = lps[j - 1 ];
30+ else
31+ i = i + 1 ;
32+ }
33+ }
34+ }
35+
36+
37+ void computeLPSArray (char * pat, int M, int * lps)
38+ {
39+
40+ int len = 0 ;
41+
42+ lps[0 ] = 0 ; // lps[0] is always 0
43+
44+
45+ int i = 1 ;
46+ while (i < M) {
47+ if (pat[i] == pat[len]) {
48+ len++;
49+ lps[i] = len;
50+ i++;
51+ }
52+ else
53+ {
54+
55+ if (len != 0 ) {
56+ len = lps[len - 1 ];
57+
58+ }
59+ else
60+ {
61+ lps[i] = 0 ;
62+ i++;
63+ }
64+ }
65+ }
66+ }
67+
68+ int main ()
69+ {
70+ char txt[] = " ABABDABACDABABCABAB" ;
71+ char pat[] = " ABABCABAB" ;
72+ KMPSearch (pat, txt);
73+ return 0 ;
74+ }
You can’t perform that action at this time.
0 commit comments