int KMPSearch(char *pat, char *txt, int M, int N){ int *longestPrefixSuffix = (int*)malloc(sizeof(int) * M); int patIndex = 0; computeLPSArray(pat, M, longestPrefixSuffix); int txtIndex = 0; while (txtIndex < N){ if (pat[patIndex] == txt[txtIndex]){ patIndex++; txtIndex++; } if (patIndex == M){ return txtIndex - patIndex; patIndex = longestPrefixSuffix[patIndex - 1]; } else if (txtIndex < N && pat[patIndex] != txt[txtIndex]){ if (patIndex != 0) patIndex = longestPrefixSuffix[patIndex - 1]; else txtIndex = txtIndex + 1; } } return -1; }
int main() { int count = 0; char inputStringArray[] = "ABABDABACDABABDABACDABABCABAB"; char patArray[] = "ABABCABAB"; int pattLen = strlen(patArray); int textLen = strlen(inputStringArray); int matchPosition = 0; // index for inputStringArray[] // create lps[] that will hold the longest prefix suffix // values for pattern int *lpsArray = (int *)calloc(pattLen, sizeof(int)); // Preprocess the pattern (calculate lps[] array) computeLPSArray(patArray, pattLen, lpsArray); for (count = 0; count < pattLen; count++) printf("%d ", lpsArray[count]); matchPosition = kmp_matcher(inputStringArray, textLen, patArray, pattLen, lpsArray); if (matchPosition != -1) printf("\nMatch found in the original input string at = %d\n", matchPosition); else printf("\nPattern Not Found The Original Input String\n"); free(lpsArray); // to avoid memory leak }
void KMPSearch(char *pat, char *txt) { int M = strlen(pat); int N = strlen(txt); // create lps[] that will hold the longest prefix suffix values for pattern int *lps = (int *)malloc(sizeof(int)*M); int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] while(i < N) { if(pat[j] == txt[i]) { j++; i++; } if (j == M) { printf("Found pattern at index %d \n", i-j); j = lps[j-1]; } // mismatch after j matches else if(pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if(j != 0) j = lps[j-1]; else i = i+1; } } free(lps); // to avoid memory leak }
void FindCount(char *pat, char *txt, int *count) { int M = strlen(pat); int N = strlen(txt); int *lps = (int *)malloc(sizeof(int)*M); int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { //printf("Found pattern at index %d \n", i - j); (*count)++; j = lps[j - 1]; } // mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } free(lps); }