字符串匹配

前几天看书,书中有一道联系题:编写一个函数,在该函数中的第一个参数中进行查找,并返回匹配第二个参数所包含的字符的数量。然后,第一种想法就是使用做笨的方法,从第一个参数的字符串从第一个字符开始到最后一个字符逐一进行匹配,为了写起来更简便一点,我借用了一些C语言的库函数,最终代码如下:

#include<stdio.h>
#include<string.h>

int count_chars( char const *str, char const *chars )
{
    int counts = 0;

    while( ( str = strpbrk( str, chars ) ) != NULL )
    {
      counts++;
      str++;
    }

    return counts;
}

但是,写完这个函数之后,突然想起来数据结构中的KMP算法也可以用来解决字符串匹配的问题。

KMP算法的代码:

#include<stdio.h>
#include<string.h>
/*KMP查找算法*/
void getNext( char *str, int *next)
{
  int plength = strlen( str );
  int k = -1;
  next[0] = -1;
  int j = 0;
  while( j < plength - 1 )
  {
    //str[j]表示前缀str[k]表示后缀
    if( k == -1 || str[j] == str[k] )
    {
      ++k;
      ++j;
      next[j] = k;
    }
    else
      k = next[k];
  }
}

int kmpserach( char *text, char *pattern, int *next )
{
  int textlength = strlen( text );
  int patternlength = strlen( pattern );
  int i = 0;
  int j = 0;

  if( text == NULL || text == NULL )
    return 0;
  while( i < textlength && j < patternlength )
  {
    if( j == -1 || text[i] == pattern[j] )
    {
      i++;
      j++;
    }
    else
      //将模式字符串移动j-next[j]位
      j = next[j];
  }
  if( j == patternlength )
    return i - j;
  else
    return -1;
}


有关KMP算法的详细说明:

http://www.cnblogs.com/c-cloud/p/3224788.html

http://blog.csdn.net/v_JULY_v/article/details/6111565

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值