模式串匹配之KMP算法代码及注释

本文深入解析KMP算法,详细讲解其核心思想、实现步骤及应用实例,帮助开发者快速掌握字符串匹配的高效解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
#include<string.h>
char str[100];
int next[100];

void Get_next(char *str, int* next)
{
 int len = strlen(str);//模式串的长度
 int i = 0;
 int j = 1;
 next[0] = 0; //下标从0开始
 while(j < len)
 {
  if(str[i] == str[j])
  {
   next[j] = next[j-1] + 1;  //当匹配时
   i++;
   j++;  
  } 
  else
   if(i == 0)
   {
    next[j] = 0;
    i++;
    j++;
   }
   else
    i = next[i];   
 }
}

int Index_KMP(char *psource, char *pstr, int *next)
{
 int i, j;
 i = 0 ;
 j = 0;
 int lens = strlen(psource); //原串的长度
 int lent = strlen(pstr); //模式串的长度
 while(i < lens && j < lent)
 {
  if(psource[i] == pstr[j])//匹配时
  {
   i++;
   j++;
  }
  else
   if(j == 0)//当j == 0时,且不匹配时,原串应该移向下一位
    i++;
   else
    j = next[j];   //不匹配
 }
 if(j >= lent)return i - lent; //匹配成功返回模式串出现的位置,注意下标是从0开始的
 else return -1;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值