Advertisement
Guest User

kolejny

a guest
Mar 28th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.60 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int dlugosc(tekst);
  5. int *init_next(char *wzor);
  6. int init_shift(char *w, int *shift);
  7. int KMP(char *tekst, char *wzor, int *next);
  8. int init_shift(char *w, int *shift);
  9.  
  10. main (){
  11.  char tekst[50], wzorzec[5];
  12.  int *next;
  13.  printf("Podaj tekst: ");
  14.  fflush(stdin);
  15.  scanf("%49[^\n]s",tekst);
  16.  printf("Podaj wzorzec: ");
  17.  fflush(stdin);
  18.  scanf("%4[^\n]s",wzorzec);
  19.  next=init_next(wzorzec);
  20.  printf("Wzorzec wystapil na: %d jezeli wartosc jest -1 to nie ma.",KMP(tekst,wzorzec,next));
  21.  getch();
  22.  
  23.  
  24. }
  25.  
  26. int dlugosc(char *tekst){
  27.     int i=0;
  28.     while(*(tekst+i)!= '\0'){
  29.         i++;
  30.     }
  31.     return i;
  32.    
  33. }
  34. int *init_next(char *wzor){
  35.     int i,j;
  36.     int M=dlugosc(wzor);
  37.     int *next = malloc(M*sizeof(int));
  38.     next[0] = -1;
  39.     for(i=0,j=-1;i<M-1;i++,j++,next[i]=j){
  40.         while((j>=0)&&(wzor[i]!=wzor[j])){
  41.             j=next[j];
  42.         }
  43.     }
  44.     return next;
  45. }
  46. int init_shift(char *w, int *shift){
  47.     int i;
  48.     int M=dlugosc(w);
  49.     shift[256];
  50.     for(i=0;i<256;i++){
  51.         shift[i]=M;
  52.     }
  53.     for(i=0;i<M;i++){
  54.         shift[w[i]]=M-i-1;
  55.     }
  56. }
  57. int KMP(char *tekst, char *wzor, int *next){
  58.     int i,j;
  59.     int N=dlugosc(tekst);
  60.     int M=dlugosc(wzor);
  61.     for(i=0,j=0;i<N&&j<M;i++,j++){
  62.         while((j>=0)&&(tekst[i]!=wzor[j])){
  63.             j=next[j];
  64.         }
  65.     }
  66.     if(j==M){
  67.         return i-M;
  68.     }else{
  69.         return -1;
  70.     }
  71. }
  72. int BM(char *tekst, char *wzor){
  73.     int i,j;
  74.     char x;
  75.     int N=dlugosc(tekst);
  76.     int M=dlugosc(wzor);
  77.     for(i=M-1,j=M-1;j>=0;i--,j--){
  78.         while(tekst[i]!=wzor[j]){
  79.             x=shift[tekst[i]];
  80.             if(M-j>x){
  81.                 i+=M-j;
  82.             }else{
  83.                 i+=x;
  84.             }
  85.             if(i>=N){
  86.                 return -1;
  87.             }
  88.             j=M-1;
  89.         }
  90.         return i+1;
  91.     }
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement