brute-force 알고리즘을 이용한 패턴 위치 찾기

by digipine posted Oct 29, 2017
?

Shortcut

PrevPrev Article

NextNext Article

ESCClose

Larger Font Smaller Font Up Down Go comment Print

// brute-force 알고리즘을 이용한 패턴 위치 찾기

#include <stdio.h>
#include <string.h>

int brutesearch();

main()
{
         char Text[] = "aababba";   
         char Pattern[] = "abb";
         
         int indexPattern = brute(Pattern, Text);

         if(indexPattern == -1)
                  printf("[Failure] Can't Find Pattern <%s>", Pattern);
                  else 
                                printf("[Success] Index of Pattern <%s> at <%s> => %d \n", Pattern, Text, indexPattern+1);
}

int brute(char *p, char *a) //brute-force 탐색 알고리즘
{
         int i, j, M=strlen(p), N=strlen(a);
         for (i=0, j=0; j<M && i<N; i++, j++){
                  while(a[i] != p[j])
                  {
                                i -= j-1;
                                j=0;
                  }
                  if (j == M) return(i-M);
                  else return (i);
         }
}

 

//출력은 [Success] Index of Pattern <abb> at <aababba> => 4
//알고리즘에 대한 설명은 교재를 참조하세요!!
//교재는 정익사 출판사의 C언어로 설명한 알고리즘 입니다.