朴素模式的匹配算法-顺序

声明:

#include "stdio.h"
#include "stdlib.h"

struct SeqString {
    int MAXNUM;
    int n;
    char *c;
};

typedef struct SeqString * PSeqString;

 

//创建空顺序串
PSeqString createNullStr_Seq(int m)
{
    PSeqString pstr=(PSeqString)malloc(sizeof(struct SeqString));
    if(pstr!=NULL)
    {
        pstr->c=(char *)malloc(sizeof(char)*m);
        if(pstr->c)
        {
            pstr->n=0;
            pstr->MAXNUM=m;
            return pstr;
        }
        else
        {
            free(pstr);
        }
    }
    printf("out of space! \n");
    return NULL;
}

 

//朴素的模式比配算法
int index(PSeqString t,PSeqString p)
{
    //求p所指的串在t所指的串中第一次出现时,p所指串的第一个元素在t所指的串中的序号
    
    //i为p串中的当前字符的下标,j为在t中当前字符的下标
    int i,j,k;
    i=0;
    j=0;

    //反复比较
    while (i<p->n&&j<t->n) 
    
        if (p->c[i]==t->c[j]) 
        {
            i++;
            j++;
        
        }
        //主串,子串的i,j值回溯,重新开始下一次匹配
        else
        {
            j=j-i+1;
            i=0;
        
        }
        //匹配成功,返回p 中第一个字符在t中的序号
        if (i>=p->n) 
        {
        
            return (j-p->n+1);
        }
        else 
        {
        
            return 0;
        }    
}

 

测试:

int main()
{
    char *c1,*c2;
    int i=0;
    PSeqString p1,p2;
    
    c1="abceabceabcd";
    c2="abcd";

    p1=createNullStr_Seq(15);
    p2=createNullStr_Seq(5);
    p1->c=c1;
    p1->n=13;

    p2->c=c2;
    p2->n=5;
    
    
    i=index(p1,p2);

    printf("%d",i);
    return 1;
}

结果输出为9;

posted on 2012-05-08 20:38  yucong  阅读(279)  评论(0)    收藏  举报

导航