Advertisement
lIlIlIlIIlI

Algorithms_KMP

Sep 9th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.69 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int main(){
  6.     char k1[100];
  7.     char k2[100];
  8.     scanf("%s", k1);
  9.     scanf("%s", k2);
  10.     int l1 = strlen(k1);
  11.     int l2 = strlen(k2);
  12.     int f1[100];
  13.     int f2[100];
  14.     int i = 0;
  15.     int j = 1;
  16.     f1[0] = 0;
  17.     for(j; j < strlen(k1); j++){
  18.         if(k1[i] == k1[j])
  19.             i++;   
  20.         else
  21.             i = 0; 
  22.         f1[j] = i;
  23.     }
  24.     int x = 0;
  25.     int y = 0; //
  26.     while(y < strlen(k2) && x < strlen(k1)){
  27.         // printf("%d, %d, %c, %c\n", x, y, k1[x], k2[y]);
  28.         if(k1[x] != k2[y]){
  29.             if(x == 0){
  30.                 y++;       
  31.             }else{
  32.                 x = f1[x-1]; // k1 的第 f1[x-1] 個對齊 k2 的第 y 個字元
  33.             }
  34.         }else{
  35.             x++;
  36.             y++;
  37.         }
  38.     }
  39.     printf("%d\n", y-x);
  40.     return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement