kmp算法实现字符串匹配

来源:互联网 发布:矩阵防御 app 编辑:程序博客网 时间:2024/05/18 07:12

今天晚上知道了这个算法,看了后凭记忆理解自己又写了一遍,日后会加上注释和思路

#include<iostream>#include<cstdio>#include<string>#include<cstring>using namespace std;void find_fun(string pstr, int *num){int i;int len = pstr.length();int index;//int* num = new int[len + 1];num[0] = -1;for (i = 1; i < len; i++){index = num[i - 1];if (pstr[i] != pstr[index + 1] && index >= 0){index = -1;}if (pstr[i] == pstr[index + 1]){index++;num[i] = index;}else{num[i] = -1;}}num[i] = '\0';for (i = 0; i < len; i++){cout << num[i] << " ";}cout << endl;}int main(){while (true){string pstr="";string str="";int i, j;cout << "输入目标字符串:" << endl;cin >> pstr;cout << "输入源字符串:" << endl;cin >> str;if (pstr == "end")break;int len = pstr.length();int n = str.length();int* num = new int[len + 1];find_fun(pstr, num);for (i = 0,j=0; (i < n)&&(j<len); ){if (pstr[j] == str[i]){j++;i++;}else{if (j == 0){i++; j++;}else{j = num[j - 1] + 1;}}}if (j == (len)){cout << "匹配成功,索引在:" << i-len << endl << "str[i-1-len]==" << str[i-len] << endl;}elsecout << "匹配不成功" << endl;}return 0;}


0 0
原创粉丝点击