第四章(4).KMP算法
来源:互联网 发布:python是用来做什么的 编辑:程序博客网 时间:2024/06/04 12:55
#include<stdio.h>
#include<stdlib.h>
#include<string.h>#define MAXSIZE 50
typedef unsigned char SString[ MAXSIZE + 1 ] ; //SString[ 0 ] 存储长度
int next[ MAXSIZE + 1 ] ;void StrAssign(SString T, char *ch)
{ //生成一个其值等于ch的串T
int i;
if(strlen(ch) > MAXSIZE)
{
exit(0);
}
else
{
T[0] = strlen(ch); //串的第一位存储串的长度(整型)
for( i = 1; i <= T[0]; i++ )
{
T[i] = *(ch + i - 1); //(字符型)
}
}
}void get_nextval( SString T , int nextval[ ] )
{ //求模式串T的next函数修正值并存入数组nextval
int i = 1 , j = 0 ;
nextval[ 1 ] = 0 ;while( i < T[ 0 ] )
{
if( j == 0 || T[ i ] == T[ j ] )
{
++ i ; ++ j ;
if( T[ i ] != T[ j ] )
nextval[ i ] = j ;
else
nextval[ i ] = nextval[ j ] ;
}
else
j = nextval[ j ] ;
}}
int Index_KMP( SString S , SString T , int pos )
{ //利用模式串T的next函数求T在主串S中第pos个字符之后的位置的KMP算法(1<= pos <= StrLength(S))
int i = pos , j = 1 ;
while( i <= S[ 0 ] && j <= T[ 0 ] )
{
if( j == 0 || S[ i ] == T[ j ] )
{
++ i ;
++ j ; //继续比较后续字符
}
else
j = next[ j ] ; //模式串向右移动
}
if( j > T[ 0 ] )
return i - T[ 0 ] ; //匹配成功
else
return 0 ;
}int main()
{
char *s = "acabaabaabcacaabc" ;
char *t = "abaabcac" ;
SString T , S ;StrAssign( S , s ) ;
StrAssign( T, t ) ;get_nextval( T , next ) ;
if( Index_KMP( S , T , 0 ) )
printf( "匹配成功\n" ) ;
else
printf( "匹配不成功\n" ) ;return 0 ;
}
- 第四章(4).KMP算法
- 第四章(串) 【KMP算法】
- 第四章 KMP模式匹配算法
- 【数据结构】第四章 串 (含KMP算法)
- 数据结构第四次上机 第四章之BF和KMP算法(顺序串的各种模式匹配算法)
- 《数据结构》严蔚敏版(java解)——第四章 串01 串的模式匹配KMP算法
- 数据结构编程笔记十一:第四章 串 定长顺序串以及模式匹配算法(BF和KMP)的实现
- <算法4>第四章图算法总结
- kmp算法(转载)
- KMP算法(转)
- (精)kmp算法
- (四)KMP算法
- KMP算法(1)
- KMP算法(2)
- KMP算法(站位)
- KMP算法(1)
- KMP算法(2)
- Period(KMP算法)
- C++扫盲系列--第一个服务器程序
- 第十一章(1).多路平衡归并排序
- 第十一章(2).置换—选择排序
- 第六章(8)求集合的幂集
- 第六章(9).四皇后问题
- 第四章(4).KMP算法
- 第四章(5).建立词索引表
- 第三章(8).离散事件模拟
- UVA 437 -- The Tower of Babylon
- 内存访问错误
- 请学好C语言![转]
- 学计算机必读[转]
- realloc重分配内存详解
- Static用法总结