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

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值