Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- int dlugosc(char* lan);
- int * init_next(char*);
- void init_shift(char*, int*);
- int KMP(char*, char*, int*);
- int BM(char*, char*);
- int * KMP_w(char*, char*, int*, int*);
- int * BM_w(char*, char*, int*);
- int main(){
- char wzor[] = "dw";
- char tekst[] = "adwiescie adwadziescia dwa";
- int next = init_next(wzor);
- int ilosc = 0;
- int * numery = KMP_w(tekst, wzor, next, &ilosc);
- //int i = KMP(tekst,wzor,next);
- printf("%d ",ilosc);
- printf("%d ",numery[0]);
- printf("%d ",numery[1]);
- printf("%d ",numery[2]);
- return 0;
- }
- int dlugosc(char *lan){
- int i = 0;
- while(lan[i] != '\0')
- i++;
- return i;
- }
- int * init_next(char * wzor){
- int M;
- int * next = 0;
- int i,j;
- M = dlugosc(wzor);
- next = realloc(next,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;
- int 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;
- }
- int * KMP_w(char * tekst, char * wzor, int * next, int * ilosc){
- int index = 0;
- int * indeksy = 0;
- *(ilosc) = 0;
- while (1) {
- index = KMP(tekst,wzor,next);
- if(index == -1)
- break;
- else{
- indeksy = realloc(indeksy,(++*(ilosc))*sizeof(int));
- tekst[index] = 'x';
- indeksy[(*ilosc) - 1] = index;
- }
- }
- return indeksy;
- }
- void init_shift(char * wzor, int * shift){
- int i, j;
- int K = 256;
- int M = dlugosc(wzor);
- for(i = 0; i < K; i++)
- shift[i] = M;
- for(i = 0; i < M; i++)
- shift[wzor[i]] = M - i - 1;
- return;
- }
- int BM(char * tekst, char * wzor){
- int shift[256];
- int M = dlugosc(wzor);
- int N = dlugosc(tekst);
- int i,j,x;
- init_shift(wzor,shift);
- 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;
- }
- int * BM_w(char * tekst, char * wzor, int * ilosc){
- int index = 0;
- int * indeksy = 0;
- *(ilosc) = 0;
- while (1) {
- index = BM(tekst,wzor);
- if(index = -1)
- break;
- else{
- indeksy = realloc(indeksy,(++*(ilosc))*sizeof(int));
- tekst[index] = 0;
- }
- }
- return indeksy;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement