HDU- KMP模板题 - 1686 Oulipo - 2087 剪花布条 - 3746 Cyclic Nacklace

1686 - 78ms:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 1000000+5;
long NEXT[MAXN];
char str1[MAXN],str2[MAXN];

void getNext()
{
    int i,j;
    NEXT[0]=-1;

    for(    i=1,j=-1;   str1[i]!='\0';    i++ )
    {
        while(  j!=-1   &&  str1[i]!=str1[j+1]  ) j=NEXT[j];
        if( str1[i]==str1[j+1]  ) j++;
        NEXT[i]=j;
    }
}

int kmp()
{
    int i,j;
    int sum=0;
    for(    i=0,j=-1;   str2[i]!='\0';    i++ )
    {
        while(  j!=-1   &&  str1[j+1]!=str2[i]  )j=NEXT[j];
        if( str1[j+1]==str2[i]  ) j++;
        if( str1[j+1]=='\0'  )//在原串中匹配str1完毕
        {
            sum++;
            j=NEXT[j];//j值回溯
        }
    }
    return sum;
}

int main()
{
    int t;
    scanf("%d",&t);
    getchar();
    while(t--)
    {
        gets(str1);
        gets(str2);
        getNext();
        printf("%d",kmp());
        puts("");
    }
    return 0;
}


2087 - 0ms:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 1000000+5;
long NEXT[MAXN];
char str1[MAXN],str2[MAXN];

void getNext()
{
    int i,j;
    NEXT[0] = -1;

    for( i = 1, j = -1; str1[i]!='\0'; ++i)
    {
        while( j!=-1 && str1[i] != str1[j+1]) j= NEXT[j];
        if( str1[i] == str1[j+1] )++j;
        NEXT[i] = j;
    }

}

int kmp()
{
    int i,j;
    int sum = 0 ;
    for( i = 0, j = -1; str2[i]!='\0'; ++i)
    {
        while( j!=-1 && str1[j+1]!=str2[i])j = NEXT[j];
        if( str1[j+1] == str2[i] )++j;
        if( str1[j+1] =='\0')
        {

            ++sum;
            j = -1; // 花条不能重叠 直接将 j 值回到 -1 从头开始匹配
        }
    }

    return sum;
}
int main()
{

    while( scanf("%s",str2) && str2[0] !='#' )
    {
        scanf("%s",str1);
        getNext();
        printf("%d",kmp());
        puts("");
    }
    return 0;
}

3746 - 109ms

#include<cstdio>
#include<cstring>
using namespace std;
const int MAXN = 100000+5;
char str[MAXN];
int NEXT[MAXN];

void getNEXT()
{
    int i,j;
    NEXT[0] = -1;
    for( i = 1 , j = -1 ; str[i]!='\0';++i )
    {
        while( j!= -1 && str[i]!= str[j+1])j = NEXT[j];
        if( str[i] == str[j+1] ) ++j;
        NEXT[i] = j;
    }
}
int main()
{
    int t;
    scanf("%d%*c",&t);
    while( t-- )
    {
        gets(str);

        getNEXT();

        int len = strlen(str);
        int ring = len - NEXT[len-1] - 1;

        if( len%ring || ring == len )
            printf("%d\n",ring-len%ring);
        else puts("0");

    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值