POJ KMP 入门题库

 出处:http://blog.csdn.net/lalor/article/details/7358956

poj 3461 Oulipo 最简单的KMP题,找出第一个字符串在第二个字符串中出现次数。  

View Code

poj 2752 Seek the Name, Seek the Fame 求子串前缀跟后缀一样的各种情况  

View Code

poj 2406 Power Strings求子串在主串中最多叠加次数  

View Code

poj 1961 Period 跟上面一题几乎一样,把主串的每一种前缀当作小主串,如果小主串的子串在小主串中叠加次数大于1,输出小主串长度及叠加次数。  

View Code
#include<stdio.h>
#include<string.h>
char s[1000003];
int next[1000004];
int n;
void getnext(char *s)
{
    int i, j;
    next[0] = -1;
    for(i = 1, j = -1; s[i]; i++)
    {
        while(j!=-1 && s[i] != s[j+1]) j = next[j];
        if(s[i] == s[j+1]) j++;
        next[i] = j;
    }
}
int main()
{
    int i, j, cas = 1;
    while( ~scanf("%d", &n) && n)
    {
        scanf("%s", s);
        getnext(s);
        int len = strlen(s);
        printf("Test case #%d\n", cas++);
        for(i = 1; i < len; i++)
            if( (i+1)%(i-next[i]) == 0 && (i-next[i]) != (i+1)) // pay attention " (i+1) == (i - next[i])"
                printf("%d %d\n", i+1, (i+1)/(i - next[i]));
        puts("");
    }
    return 0;
}

 

 

posted @ 2012-11-20 23:11  To be an ACMan  Views(496)  Comments(0)    收藏  举报