Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <conio.h>
- #include <stdlib.h>
- int dlugosc(char*lan);
- int *init_next(char*wzor);
- int KMP(char*tekst,char*wzor,int*next);
- void init_shift(char*wzor,int*shift);
- //int BM(char *tekst,char*wzor);
- main()
- {
- int N,M,P,L,*i=NULL;
- char lancuch[100];
- char wzorzec[30];
- printf("Podaj lancuch: \n");
- fflush(stdin);
- scanf("%99[^\n]s",lancuch);
- printf("Podaj wzorzec: \n");
- fflush(stdin);
- scanf("%29[^\n]s",wzorzec);
- i=init_next(wzorzec);
- printf("%d", i[5]);
- P=KMP(lancuch,wzorzec,i);
- if(P!=-1)
- printf("Znaleziono wzorzec w tekscie.\nZnajduje sie on w indeksie %d\n",P+1);
- else
- printf("Nie znaleziono wzorca.\n");
- //L=BM(lancuch,wzorzec);
- //if(L!=-1)
- //printf("Znaleziono wzorzec w tekscie.\nZnajduje sie on w indeksie %d\n",L);
- //else
- //printf("Nie znaleziono wzorca.\n");
- //printf("Podany lancuch ma dlugosc %d\n",N);
- system("pause");
- getchar();
- return(0);
- }
- int dlugosc(char*lan)
- {
- int i=0;
- int d=0;
- while(lan[i]!='\0')
- {
- d=d+1;
- i++;
- }
- return d;
- }
- int *init_next(char*wzor)
- {
- int *next=NULL;
- int i,j,M;
- M=dlugosc(wzor);
- next=(int*)malloc(M*sizeof(int));
- next[0]=-1;
- for(i=0,j=-1;i<M-1;i++,j++,next[i]=j){
- while((j>=0)&&(wzor[i]!=wzor[j])){
- j=next[j];
- }
- }
- return next;
- }
- int KMP(char*tekst,char*wzor,int *next)
- {
- int i,j,N,M;
- N=dlugosc(tekst);
- M=dlugosc(wzor);
- for(i=0,j=0;i<N&&j<M;i++,j++)
- while((j>=0)&&(tekst[i]!=wzor[j]))
- j=next[j];
- if(j==M)
- return i-M;
- else
- return -1;
- }
- void init_shift(char*wzor,int*shift)
- {
- int K=256,i,M;
- M=dlugosc(wzor);
- for(i=0;i<K;i++)
- shift[i]=M;
- for(i=0;i<M;i++)
- shift[wzor[i]]=M-i-1;
- }
- //int BM(char*tekst,char*wzor)
- //{
- // int i,j,x,M,N;
- // N=dlugosc(tekst);
- // M=dlugosc(wzor);
- // int *shift=NULL;
- // if(M>N)
- // {
- // return -1;
- // }
- // for(i=M-1,j=M-1;j>=0;i--,j--)
- // while(tekst[i]!=wzor[j])
- // {
- // x=shift[tekst[i]];
- // if(M-j>x)
- // i+=M-j;
- // else
- // i+=x;
- // if(i>=N)
- // {
- // return -1;
- // }
- // j=M-1;
- // }
- // return i+1;
- //}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement