« 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_MIN11#include <unordered_map>12using namespace std;1314void computeLPSArray(string pat, int M, int* lps)15{16 int len = 0;17 lps[0] = 0; // lps[0] is always 01819 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}3536void KMPSearch(string pat, string txt){37 int M = pat.length();38 int N = txt.length();3940 int lps[M];4142 computeLPSArray(pat, M, lps);4344 int i = 0;45 int j = 0;46 while ((N - i) >= (M - j)) {47 if (pat[j] == txt[i]) {48 j++;49 i++;50 }5152 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 anyway58 if (j != 0){59 j = lps[j - 1];60 }else{61 i = i + 1;62 }6364 }65 }66}6768int main()69{70 string txt = "AABAACAADAABAABA";71 string pat = "AABA";72 KMPSearch(pat, txt);73 return 0;74}