Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- int dlugosc(char *lan);
- int* init_next(char *wzor);
- int KMP(char *tekst, char *wzor, int *next);
- int* KMP_w(char* tekst, char* wzor, int* next, int* ilosc);
- int main()
- {
- char string[50];
- char pattern[50];
- int *next, index, *table_of_index, counter=0, i;
- do
- {
- printf("\nPodaj lancuch: ");
- fflush(stdin);
- scanf("%s", string);
- printf("\nPodaj wzor: ");
- fflush(stdin);
- scanf("%s", pattern);
- next=init_next(pattern);
- index=KMP(string, pattern, next);
- if(index==-1)
- printf("Nie znaleziono wzorca w tekscie!");
- else
- {
- printf("Wzorzec na pozycji: %d \n",index);
- table_of_index=KMP_w(string,pattern,next,&counter);
- printf("\nZnaleziono: %d wzorow\n",counter);
- if(counter>1)
- {
- for(int i=0; i<counter; i++)
- {
- printf("\n%d",table_of_index[i]);
- }
- }
- else
- {
- printf("Znaleziono tylko jeden wzor\n");
- }
- }
- }while(index != -1);
- return 0;
- }
- int dlugosc(char *lan)
- {
- int length=0;
- while(lan[length]!='\0')
- {
- length++;
- }
- return length;
- }
- int *init_next(char *wzor)
- {
- int *next=NULL;
- int i, j, p_length=dlugosc(wzor);
- for(i=0, j=-1; i<p_length; i++, j++)
- {
- next=(int*)realloc(next, (i+1)*sizeof(int));
- 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=0, j=0, p_length=dlugosc(wzor), s_length=dlugosc(tekst);
- for (i=0, j=0; j<p_length &&i<s_length; i++,j++)
- {
- while((j>=0) && (tekst[i]!=wzor[j]))
- j=next[j];
- }
- if(j==p_length)
- return i-p_length+1;
- else
- return -1;
- }
- int* KMP_w(char* tekst, char* wzor, int* next, int* ilosc)
- {
- int i=0, j=0, p_length=dlugosc(wzor), s_length=dlugosc(tekst);
- int* table_of_index=NULL;
- while(i<=s_length-p_length)
- {
- for (i, j=0; j<p_length &&i<s_length; i++,j++)
- {
- while((j>=0) && (tekst[i]!=wzor[j]))
- j=next[j];
- }
- if(j==p_length)
- {
- *ilosc+=1;
- table_of_index=(int*)realloc(table_of_index,(*ilosc)*sizeof(int));
- table_of_index[*ilosc-1]=i-p_length+1;
- i=i-p_length+1;
- }
- else
- break;
- }
- return table_of_index;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement