Advertisement
STANAANDREY

wildcard kmp

Nov 22nd, 2023
908
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.24 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. void computeLPSArray(char *pat, int M, int *lps) {
  6.     int len = 0;
  7.     lps[0] = 0;
  8.  
  9.     int i = 1;
  10.     while (i < M) {
  11.         if (pat[i] == pat[len]) {
  12.             len++;
  13.             lps[i] = len;
  14.             i++;
  15.         } else {
  16.             if (len != 0) {
  17.                 len = lps[len - 1];
  18.             } else {
  19.                 lps[i] = 0;
  20.                 i++;
  21.             }
  22.         }
  23.     }
  24. }
  25.  
  26. void kmpWildcardSearch(char *pat, char *txt) {
  27.     int M = strlen(pat);
  28.     int N = strlen(txt);
  29.  
  30.     int *lps = (int *)malloc(sizeof(int) * M);
  31.     computeLPSArray(pat, M, lps);
  32.  
  33.     int i = 0;
  34.     int j = 0;
  35.     while (i < N) {
  36.         if (pat[j] == txt[i] || pat[j] == '*') {
  37.             j++;
  38.             i++;
  39.         }
  40.  
  41.         if (j == M) {
  42.             printf("Pattern found at index %d\n", i - j);
  43.             j = lps[j - 1];
  44.         } else if (i < N && (pat[j] != txt[i] && pat[j] != '*')) {
  45.             if (j != 0)
  46.                 j = lps[j - 1];
  47.             else
  48.                 i++;
  49.         }
  50.     }
  51.  
  52.     free(lps);
  53. }
  54.  
  55. int main() {
  56.     char txt[] = "afjkarbdsabacba";
  57.     char pat[] = "a*b";
  58.  
  59.     kmpWildcardSearch(pat, txt);
  60.  
  61.     return 0;
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement