1. 程式人生 > >KMP模版 && KMP求子串在主串出現的次數模版

KMP模版 && KMP求子串在主串出現的次數模版

next() bsp blog ext font next while creat count()

int next[MAX_LEN];
void creat_next(char *S, int Sn)
{
    int k, q;
    next[0] = 0;
    for(k=0, q=1; q<Sn; q++){
        while(k>0 && S[k]!=S[q]) k = next[k-1];
        if(S[k] == S[q]){
            k++;
        }
        next[q] = k;
    }
}
bool Judge(char *S, char *T, int Sn, int Tn)//
S是子串,T是主串 { int q, i; for(i=0, q=0; i<Tn&&q<Sn; i++){ while(q>0 && S[q]!=T[i]) q = next[q-1]; if(S[q] == T[i]) q++; } return (q == Sn)?true:false; }

求次數

int next[maxn];  
char S[maxn], T[maxn * 100];  
void creat_next() {  
    int i = 0
, j = -1; next[i] = j; while(S[i]) { if(j == -1 || S[i] == S[j]) { ++i; ++j; if(S[i] == S[j]) next[i] = next[j]; else next[i] = j; } else j = next[j]; } } int KMP_count() { creat_next();
int i = 0, j = 0, ans = 0; while(T[i]) { if(j == -1 || T[i] == S[j]) { ++i; ++j; if(!S[j]) { ++ans; j = next[j]; } } else j = next[j]; } return ans; }

KMP模版 && KMP求子串在主串出現的次數模版