hiho-1015(c++)

来源:互联网 发布:网上怎么开淘宝 编辑:程序博客网 时间:2024/06/06 09:05

20150204

KMP算法

字符串匹配

代码:

#include <iostream>using namespace std;string mode;string source;int next[10000];int counts;int main(){    int n;    cin >> n;    for(int i = 0; i < n; i++){        cin >> mode >> source;        counts = 0;        for(int k = 1; k < mode.length(); k++){            if(mode[k]==mode[counts]){                counts++;            }else{                counts = 0;                if(mode[k]==mode[counts]){                    counts++;                }            }            next[k] = counts;        }        counts = 0;        int n = 0;        for(int j = 0; j < source.length(); j++){            if(source[j]==mode[counts]){                counts++;                if(counts == mode.length()){                    n++;                    counts = next[counts-1];                }            }else{                if(counts == 0)                    continue;                j--;                counts = next[counts-1];            }        }        cout << n << endl;    }    return 0;}


0 0