« Find indices of all occurrence of one string in other

Input :

GeeksforGeeks

Geeks

Output : 0 8

Input :

GFG

g

Output : NONE

1#include<iostream>
2#include<iomanip>
3#include<algorithm>
4#include<string>
5#include<cstring>
6#include<vector>
7#include<cmath>
8#include <map>
9#include<climits>
10//climits for INT_MIN
11#include <unordered_map>
12using namespace std;
13
14void computeLPSArray(string pat, int M, int* lps)
15{
16 int len = 0;
17 lps[0] = 0; // lps[0] is always 0
18
19 int i = 1;
20 while (i < M) {
21 if (pat[i] == pat[len]) {
22 len++;
23 lps[i] = len;
24 i++;
25 }else if (pat[i] != pat[len]){
26 if (len != 0) {
27 len = lps[len - 1];
28 }else if(len == 0){
29 lps[i] = 0;
30 i++;
31 }
32 }
33 }
34}
35
36void KMPSearch(string pat, string txt){
37 int M = pat.length();
38 int N = txt.length();
39
40 int lps[M];
41
42 computeLPSArray(pat, M, lps);
43
44 int i = 0;
45 int j = 0;
46 while ((N - i) >= (M - j)) {
47 if (pat[j] == txt[i]) {
48 j++;
49 i++;
50 }
51
52 if (j == M) {
53 printf("Found pattern at index %d ", i - j);
54 j = lps[j - 1];
55 }else if (i < N && pat[j] != txt[i]) {
56 // Do not match lps[0..lps[j-1]] characters,
57 // they will match anyway
58 if (j != 0){
59 j = lps[j - 1];
60 }else{
61 i = i + 1;
62 }
63
64 }
65 }
66}
67
68int main()
69{
70 string txt = "AABAACAADAABAABA";
71 string pat = "AABA";
72 KMPSearch(pat, txt);
73 return 0;
74}