LC 466. Count The Repetitions

link

class Solution {
public:
    int getMaxRepetitions(string s1, int n1, string s2, int n2) {
        int len2=s2.size();
        int len1=s1.size();
        vector<int> next(len2);
        vector<int> cnt(len2);
        for(int i=0;i<len2;i++){
            int idx=i;
            for(int j=0;j<s1.size();j++){
                if(s2[idx]==s1[j]){
                    idx++;
                    if(idx==len2){
                        cnt[i]++;
                        idx=0;
                    }
                }
            }
            next[i]=idx;
        }
        vector<int> idxToRound(len2,-1);
        int idx=0;
        int totalcnt=0;
        for(int i=1;i<=n1;i++){
            if(idxToRound[idx]!=-1){
                int patternlen=i-idxToRound[idx];
                int precnt=0;
                int firstidx=0;
                while(firstidx!=idx){
                    precnt+=cnt[firstidx];
                    firstidx=next[firstidx];
                }
                int patterncnt=totalcnt-precnt;
                int middlecnt=(n1-idxToRound[idx]+1)/patternlen*patterncnt;
                int remain=(n1-idxToRound[idx]+1)%patternlen;
                int suffix=0;
                firstidx=idx;
                for(int j=1;j<=remain;j++){
                    suffix+=cnt[firstidx];
                    firstidx=next[firstidx];
                }
                return (precnt+middlecnt+suffix)/n2;
            }
            idxToRound[idx]=i;
            totalcnt+=cnt[idx];
            idx=next[idx];
        }
        return totalcnt/n2;
    }
};
原文地址:https://www.cnblogs.com/FEIIEF/p/12734830.html