class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 计算模板串S在文本串T中出现了多少次
     * @param S string字符串 模板串
     * @param T string字符串 文本串
     * @return int整型
     */

    vector<int> get_next(string S)
    {
        int n = S.length();
        vector<int> next(n);
        next[0] = -1;
        for(int i = 1, j = -1; i < n; ++i){
            while(j >= 0 && S[i] != S[j + 1])
            {
                j = next[j];
            }
            if(S[i] == S[j + 1])
            {
                ++j;
            }
            next[i] = j;
        }
        return next;
    }

    int kmp(string S, string T) 
    {
        int sn = S.length(), tn = T.length();
        vector<int> next{get_next(S)};
        int r = 0;
        if(sn > tn)
        {
            return r;
        }
        for(int i = 0, j = -1; i < tn; ++i)
        {
            while(j >= 0 && T[i] != S[j + 1])
            {
                j = next[j];
            }
            if(T[i] == S[j + 1])
            {
                ++j;
            }
            if(j + 1 == sn)
            {
                ++r;
                j = next[j];
            }
        }
        return r;
    }
};