题目描述
学习KMP算法,给出主串和模式串,求模式串在主串的位置
算法框架如下,仅供参考
输入
第一个输入t,表示有t个实例
第二行输入第1个实例的主串,第三行输入第1个实例的模式串
以此类推
输入样例:
3
qwertyuiop
tyu
aabbccdd
ccc
aaaabababac
abac
输出
第一行输出第1个实例的模式串的next值
第二行输出第1个实例的匹配位置,位置从1开始计算,如果匹配成功输出位置,匹配失败输出0
以此类推
输出样例:
-1 0 0
5
-1 0 1
0
-1 0 0 1
8
代码
#include <iostream>
using namespace std;
class StringMatch{
public:
    string S,T;
    int slen,tlen;
    int *next;
    StringMatch(){
        cin >> S >> T;
        slen = S.length();
        tlen = T.length();
        next = new int[tlen+1];
        getNext(T,next);
        for(int i = 1; i <= tlen; i++){
            cout << next[i] << " ";
        }
        cout << endl;
    }
    void getNext(string T, int *next){  //得到next数组
        next[1] = 0;
        int i = 1, j = 0;
        while(i < tlen){
            if(j == 0 || T[j-1] == T[i-1]){
                i++;
                j++;
                next[i] = j;
            }else{
                j = next[j];
            }
        }
        for(int i = 1; i <= tlen; i++){  //题目中next从-1开始
            next[i]--;
        }
    }
    int KPM(){
        int i = 0, j = 0;
        while(i <= slen && j <= tlen){
            if(j == -1 || S[i] == T[j]){
                i++;
                j++;
            }else{
                j = next[j+1];
            }
            if(j > tlen-1){
                return i-tlen+1;
            }
        }
        return 0;
    }
};
int main()
{
    int t;
    cin >> t;
    while(t--){
        StringMatch key;
        int res = key.KPM();
        cout << res << endl;
    }
    return 0;
}
                




















