POJ2406 字符串最小循環節

給出一些字符串,求每個字符串中其所有子串最多出現的次數。

利用KMP的next數組求最小循環節。

如果n%(n-next[n])==0,則存在重複連續子串,長度爲n-next[n]

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std ;

const int maxn = 1e6+10 ;
char tar[maxn] ;
int n, m, nxt[maxn] ;

int main() {
    int i, j, k ;
    while ( scanf ( "%s", tar+1 ) != EOF ) {
        if ( tar[1] == '.' ) return 0 ;
        memset ( nxt, 0, sizeof(nxt) ) ;
        n = strlen(tar+1) ;

        for ( i = 2, j = 0 ; i <= n ; i ++ ) {
            for ( ; j && tar[j+1] != tar[i] ; j = nxt[j] ) ;
            if ( tar[j+1] == tar[i] ) ++ j ;
            nxt[i] = j ;
        }

        int ans = 1 ;
        if ( n%(n-nxt[n]) == 0 ) ans = n/(n-nxt[n]) ;
        printf ( "%d\n", ans ) ;
    }
    return 0 ;
}
發佈了55 篇原創文章 · 獲贊 39 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章