KMP算法的实现

来源:互联网 发布:广州星知电子有限公司 编辑:程序博客网 时间:2024/05/19 03:45

本文来自hihoCoder1015题,已AC。统计字符串中出现的模式串的次数。
对于有两个字符串:
源字符串:ababcabcababcabcab
….模式串:abcabc
next数组:-1 0 0 0 1 2
匹配过程如下:
|a|b|a|b|c|a|b|c|a|b|a|b|c|a|b|c|a|b|
|–|–|a|b|c|a|b|c|–|–|–|–|–|–|–|–|–|–|
|–|–|–|–|–|a|b|c|a|b|c|–|–|–|–|–|–|–|
|–|–|–|–|–|–|–|–|–|–|a|b|c|a|b|c|–|–|
参考文献:
KMP算法学习&总结
代码如下:

#include <iostream>#include <vector>#include <string>using namespace std;void getNext(const string &pattern, vector<int> &next){    next.resize(pattern.size());    next[0] = -1;    int i = 0, j = -1;    while(i != pattern.size() - 1) {        if(j == -1 || pattern[i] == pattern[j]) {            i++;            j++;            next[i] = j;        } else {            j = next[j];        }    }}int kmp(const string &source, const string &pattern){    vector<int> next(pattern.size());    getNext(pattern, next);    int i = 0, j = 0;    int count = 0;    while(i != source.length() && j != pattern.length()) {        if(j == -1 || source[i] == pattern[j]) {            i++;            j++;        } else {            j = next[j];        }        if(j == pattern.length()) {//匹配到一个模式串后做处理,减少匹配次数            count++;            i--;            j = next[j - 1];        }    }    return count;}int main(){    int N;    cin >> N;    string p, s;    while(N--) {        cin >> p;        cin >> s;        cout << kmp(s, p) << endl;    }    return 0;}
0 0
原创粉丝点击