您的位置:首页 > 其它

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

2013-08-22 10:01 246 查看
#include <stdio.h>

#include <stdlib.h>

#include <string.h>

理解:用record来记录位移  对每一个可能的位移  比较匹配串和主串子串是否相等。

int Index(char *f,char*c)//father child

{

    int fcnt,ccnt,record=0;

    for (fcnt=record,ccnt=0;f[fcnt]&&c[ccnt];)//注意此处for循环的出口可以更近  可以更高效。f根本不用比到末尾  只要剩下的字符串的长度不够c了  就可以结束了

    {

        if (f[fcnt]==c[ccnt])

        {

            fcnt++;

            ccnt++;

        }

        else

        {

            record++;

            fcnt=record;

            ccnt=0;

        }

    }

    if (!c[ccnt]) return record+1;

    else return 0;

}

int main()

{

    int n,i;

    char a[20];

    char b[20];

    while (1)

    {

        printf("Input string 1:\n");

        gets(a);

        printf("Input string 2:\n");

        gets(b);

        n=Index(b,a);

        if(n)

        {

            for (i=0;i<n-1;i++)printf(" ");

            puts(a);

        }

        else

            printf("unmatched\n");

        printf("\n");

    }

    return 0;
}

改进版

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int Index(char *f,char*c)//father child

{

    int fcnt,ccnt,record=0;                                                               //record记录模式串在主串中的位移  0=<record&&record+length(c)<=length(f)

    int lenf,lenc;

    lenf=strlen(f);

    lenc=strlen(c);

    for (fcnt=record,ccnt=0;record<=lenf-lenc&&c[ccnt];)

    {

        if (f[fcnt]==c[ccnt])

        {

            fcnt++;

            ccnt++;

        }

        else

        {

            record++;

            fcnt=record;

            ccnt=0;

        }

    }

    if (!c[ccnt]) return record+1;

    else return 0;

}

int main()

{

    int n,i;

    char a[20];

    char b[20];

    while (1)

    {

        printf("Input string 1:\n");

        gets(a);

        printf("Input string 2:\n");

        gets(b);

        n=Index(b,a);

        if(n)

        {

            for (i=0;i<n-1;i++)printf(" ");

            puts(a);

        }

        else

            printf("unmatched\n");

        printf("\n");

    }

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: