KMP算法2018-05-28

include <stdio.h>

include <stdlib.h>

include <string.h>

/Kmp匹配算法,根据自己的理解所写,可能有待改进; 2018/5/28/
/发现在运行窗口中复制粘贴是一件很麻烦的事情;/

void table_date(char a[],int array[10])
{
int k=0,i=0,j=0,cur = 0;
int length = strlen(a);
for(k=2;k<=length;k++)
{
for(i=1;i<k;i++)
{
for(j=0;j<i;j++)
{
if(a[j] != a[k-i+j]) //k = length - i +j
break;
}
if(i == j)cur = j;
}
array[k-1] = cur;
cur = 0;
}
array[0] = 0;
}
int main()
{
char target_string[1000]; //用于存储目标字符串
char match_string[1000]; //用于存储匹配字符串
int length_target,lenght_match,counter=0;//counter计算匹配个数
int integer_table[100],i=0,k=0;
printf("please input target strings:");
gets(target_string);
printf("please input match strings:");
gets(match_string);
table_date(target_string,integer_table);
length_target = strlen(target_string); //匹配字符串长度
lenght_match = strlen(match_string); //目标字符串长度
for(i=0;i<length_target;i++)
{
while(k<lenght_match)
{
if(target_string[i+k]==match_string[k])k++;
else
{
i+=k-integer_table[k];
break;
}
}
if(k==lenght_match)
counter++; //此处的分号用‘;’用‘,’也正确;
i+=lenght_match-1;
k=0;
}
printf("This match string is appearance %d times;",counter);
return 0;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 6,156评论 0 2
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,742评论 0 38
  • 回溯算法 回溯法:也称为试探法,它并不考虑问题规模的大小,而是从问题的最明显的最小规模开始逐步求解出可能的答案,并...
    fredal阅读 14,685评论 0 89
  • 日子过得就像每天不变的蔬菜,白菜土豆胡萝卜轮流来。我还是想把这一去不复返的平淡生活和稍纵即逝的想法情感转化为文字记...
    知知知知鸟阅读 2,939评论 0 0
  • K82列车行了一个昼夜,次日清晨临近九点才到达了河南信阳。我的目的地是汝州,数了数行程,还有五个站九个多小时的路程...
    仓央格桑阅读 2,532评论 0 0