【算法分析】字符串匹配:BF、KMP算法

来源:互联网 发布:缺乏信任感知乎 编辑:程序博客网 时间:2024/05/24 15:41

字符串匹配算法:BF、KMP算法代码。

/*****************************************  Copyright (c) 2015 Jingshuang Hu    @filename:demo.c  @datetime:2015.10.11  @author:HJS  @e-mail:eleftheria@163.com  @blog:http://blog.csdn.net/hujingshuang  *****************************************/#include <stdio.h>#include <stdlib.h>#include <string.h>#include <iostream>using namespace std;/**************************************************/int text_read(char *S);void BF_String_Matching(char *S, char *T);void KMP_String_Matching(char *S, char *T);int *Partial_Matching_Table(char *T);/**************************************************/int main(){char *S = (char *)malloc(1000 * sizeof(char));char T[100];text_read(S);printf("给定文本串:\n%s", S);printf("\n输入模式串:\n");gets(T);printf("\n-------BF算法-------\n");BF_String_Matching(S, T);printf("\n-------KMP算法------\n");KMP_String_Matching(S, T);printf("\n\n");return 0;}/**************************************************/int text_read(char *S){int len = 0;char ch;FILE *fp = fopen("test.txt","r");if (!fp){printf("打开文件失败!\n");return 1;}while((ch = getc(fp)) != EOF){S[len] = ch;len++;}fclose(fp);S[len] = '\0';S = (char *)realloc(S, (len + 1) * sizeof(char));return 0;}/**************************************************///暴力法void BF_String_Matching(char *S, char *T){int S_length = strlen(S);int T_length = strlen(T);int i = 0, j = 0, same_length = 0;for (i = 0; i < S_length - T_length; i++){for (j = 0; j < T_length; j++){if (S[i + j] == T[j]){same_length++;}else{break;}}if (same_length == T_length){printf("在位置%d发现匹配!\n", i + 1);}same_length = 0;}}/**************************************************///KMP   移动位数 = 已匹配的字符数 - 对应的部分匹配值void KMP_String_Matching(char *S, char *T){int *table = Partial_Matching_Table(T);//获取部分匹配表int S_length = strlen(S);int T_length = strlen(T);int i = 0, j = 0;int same_length = 0, move_pos = 0;for (i = 0; i < S_length - T_length; i++){if (S[i + 0] != T[0])//第一个字符都不等,则后移一位{continue;}else//否则,继续对比后面字符{same_length++;for (j = 1; j < T_length; j++){if (S[i + j] == T[j]){same_length++;//已匹配数}else{move_pos = table[j - 1];break;}}}if (same_length == T_length){printf("在位置%d发现匹配!\n", i + 1);i += T_length - 1;//直接往后移动T_length位}else{i += same_length - move_pos - 1;//移动后i的位置}same_length = 0;}}/**************************************************///部分匹配表int *Partial_Matching_Table(char *T){int T_length = strlen(T);int *table = (int *)malloc(T_length * sizeof(int));int k = -1, i = 0, j = 0;memset(table, 0, T_length);//全部初始化成0table[0] = -1;while(j < T_length){if ((-1 == k) || (T[k] == T[j])){j++;k++;table[j] = k;}else{k = table[k];}}for (i = 0; i < T_length; i++){table[i] = table[i + 1];}table = (int *)realloc(table, T_length * sizeof(int));return table;}

3 0
原创粉丝点击