前几天看书,书中有一道联系题:编写一个函数,在该函数中的第一个参数中进行查找,并返回匹配第二个参数所包含的字符的数量。然后,第一种想法就是使用做笨的方法,从第一个参数的字符串从第一个字符开始到最后一个字符逐一进行匹配,为了写起来更简便一点,我借用了一些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.youkuaiyun.com/v_JULY_v/article/details/6111565