kmp算法的c代码实现

 

#include 
 
 
  
  
#include 
  
  
   
   
#include 
   
   
    
    

/************************************************* 
*函数功能:将制定的字符串中的next值放入一个数组中 
*参    数:str为字符串,next为数字数组 
*返    回:无 
*说    明:改函数实际是将target串于自己中的子字符串匹配,
* 计算target中的字符不匹配时的回溯值。 
**************************************************/
void get_next(char *str, int *next)
{
     int i = 1;
     int j = -1;
     
     /*与第一个字符不匹配,就不进行回溯,直接与下一个进行匹配*/
     next[0] = -1;     
     for (i = 0, j = -1; i < strlen(str);)
     {
         if ((j == -1) || (str[i] == str[j]))
         {
             //匹配相同或者是与第一个都不匹配 
             i++;
             j++;
             next[i] = j;
         }
         else
         {
             //匹配不相同,进行回溯 
             j = next[j];
         }
     }
     
     return ;
}



/*********************************************************
*函数功能:在主串中匹配已有的子串 
*参    数:source是主串,target是子字符串 
*返    回:成功返回子串在主串中的位置,失败返回-1 
*说    明:kmp算法较传统的匹配算法在一些特定场合可以提高效率。 
**********************************************************/
int my_match(char *source, char *target)
{
    int source_len = strlen(source);
    int target_len = strlen(target);
    int i = 0;
    int j = 0;

    int *next = NULL;
    
    next = (int *)malloc(target_len);
    if (next == NULL)
    {
        printf("malloc memory is failed! /n");
        return -1;
    }
    
    get_next(target, next);
   
    for (i = 0, j = 0; (i < source_len) && (j < target_len);)
    {
        if ((j == -1) || (source[i] == target[j]))
        {
            i++;
            j++;
        }
        else
        {
            j = next[j];
        }
    }
    
    free(next);
    
    if (j >= target_len)
    {
        //返回字串在主串中的第sum个位置 
        return (i - target_len + 1);
    }
    else
    {
        return -1;
    }
}


int main()
{
    char *source = "abcabcabdccd";
    char *target = "abcabd";
    int sum = 0;
    
    sum  = my_match(source, target);
    printf("%d/n", sum);
    getch();
    
    return 0;
}
    
    

   
   
  
  
 
 

 

 

在dev-cpp下编译通过。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值