File tree 1 file changed +54
-0
lines changed
1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Knuth-Patt-Morris Algorithm for pattern searching in given string
2
+
3
+
4
+ /*
5
+ txt is text and pat is the pattern to be searched
6
+ vector pos stores the end position where pattern is found
7
+ (0-based indexing)
8
+ Time Conmplexity: O(pat.length + txt.length)
9
+ */
10
+
11
+ #include < bits/stdc++.h>
12
+ using namespace std ;
13
+
14
+ vector<int > kmp (string txt, string pat)
15
+ {
16
+ string s = pat + ' $' + txt;
17
+ int n = s.length (), l = pat.length ();
18
+ vector<int > LPS (n, 0 );
19
+ int k = 0 ;
20
+
21
+ /* Building LPS Array */
22
+ for (int i = 1 ; i < n; ++i)
23
+ {
24
+ while (k > 0 && s[i] != s[k])
25
+ {
26
+ k = LPS[k-1 ];
27
+ }
28
+ if (s[i] == s[k])
29
+ ++k;
30
+ LPS[i] = k;
31
+ }
32
+ /* Searching for pattern and storing occurences in vector i.e the index where pattern ends */
33
+ vector<int > pos;
34
+ for (int i = 0 ; i < n; ++i)
35
+ {
36
+ if (LPS[i] == l)
37
+ {
38
+ pos.push_back (i-l-1 );
39
+ }
40
+ }
41
+ return pos;
42
+ }
43
+
44
+ int main ()
45
+ {
46
+ string text,pattern;
47
+ cin>>text>>pattern;
48
+ vector<int > ans=kmp (text,pattern);
49
+ for (auto y:ans)
50
+ {
51
+ cout<<y+1 <<endl;
52
+ }
53
+ return 0 ;
54
+ }
You can’t perform that action at this time.
0 commit comments