POJ2406 Power String

這道題的大意是:
給出若干字符串,求每個字符串的最小構成子串(從字符串的頭開始),即由該子串不斷重複能構成所給出的字符串。
主要是kmp的應用。

首先,使用暴力的方法能過。時間複雜度高,空間複雜度低。
枚舉子串的長度,該長度應能被整個字符串的長度整除。將子串與字符串遍歷比較,若有不同則枚舉下一個子串。對子串可以用加一模除整個子串長度,來擴展成語字符串相同的長度。
#include <algorithm>
#include <string.h>
#include <math.h>
#include <stdio.h>
const int max = 10000001;
char Str[max];

int main() {
    while (scanf("%s", Str) && Str[0] != '.') {
        int chnum = 1;
        int len = strlen(Str);

        for (chnum = 1; chnum <= len; chnum++) {
            int cishu = len%chnum;
            if (cishu) continue;
            if (chnum == len) {
                printf("1\n");
                break;
            }

            int i = 0, j = 0;
            for (i = 0; i < len; i++) {
                if (Str[i] != Str[j]) break;
                else j = (j+1)%chnum;
            }

            if (i >= len) {
                printf("%d\n", len/chnum);
                break;
            }
        }
    }
    return 0;
}
可以用kmp算法中,構造next數組的思想。
next數組存放的是當前字符要與之比較的字符,在這兩個字符之前的字符都相同。
當每個字符均不同時要特判。
#include <algorithm>
#include <string.h>
#include <math.h>
#include <stdio.h>

const int max = 10000001;
char Str[max];
int next[max];
void get_next(int len) {
    int i = 0, j = -1;
    next[0] = -1;
    while(i < len) {
        if (j == -1 || Str[i] == Str[j]) {
            ++i; ++j;
            next[i] = j;
        }
        else j = next[j];
    }   
    return;
}

int main() {
    while (scanf("%s", Str) && Str[0] != '.') {
        int len = strlen(Str);
        get_next(len);
        int num = len-next[len];
        if (len%(num) == 0) printf("%d\n", len/(num));
        else printf("1\n");
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章