#1015 : KMP算法

来源:互联网 发布:ubuntu 64 位.vmdk 编辑:程序博客网 时间:2024/06/18 10:21

题目及解答

详细的可以看数据结构书(C语言版)严蔚敏 P80页。我觉得那个讲解比较清楚一些。

代码

这是我重写的代码

#include<iostream>#include<string>using namespace std;#define max 10005int ne[max];int main(){    string s, s1;    int i, j;    int N;    int ans;    while (cin >> N){        while (N--){            cin >> s;            cin >> s1;            ans = 0;            //构建next数组            i = 1; ne[1] = 0; j = 0;            while (i <= s.length()){                if (j == 0 || s[i - 1] == s[j - 1]){ ++i; ++j; ne[i] = j; }                else                    j = ne[j];            }            //显示next数组            /*  for (i = 1; i <= s.length (); i++)            cout << next[i] << " ";            cout << endl;*/            //KMP匹配            int len = s.length();            for (i = 0, j = 1; i < s1.length();){                if (j == 0 || s[j - 1] == s1[i]){                    i++;                    j++;                }                else                    j = ne[j];                if (j == len+1)ans++;            }            cout << ans << endl;        }    }    return 0;}
0 0
原创粉丝点击