uva455 Periodic Strings

因为对strncpy函数不熟练所以wa了几次还找不到原因,最后发现是strcpy重新复制时,若新复制的字符串短,原有比新串长的部分会被保留。所以每次复制前要使用memset函数。

刚学习,代码比较简陋,效率也不高。

A character string is said to have period k if it can be formed by concatenating one or more repetitionsof another string of length k. For example, the string ”abcabcabcabc” has period 3, since it is formedby 4 repetitions of the string ”abc”. It also has periods 6 (two repetitions of ”abcabc”) and 12 (onerepetition of ”abcabcabcabc”).Write a program to read a character string and determine its smallest period.

Input

The first line oif the input file will contain a single integer N indicating how many test case that yourprogram will test followed by a blank line. Each test case will contain a single character string of upto 80 non-blank characters. Two consecutive input will separated by a blank line.

Output

An integer denoting the smallest period of the input string for each input. Two consecutive output areseparated by a blank line.

Sample Input

1

HoHoHoSample

Output

2

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int macth_string(char*, char*, int, int);

char s[1000];
char ss[1000];

int main()
{
    int t = 0;
    scanf("%d", &t);
    while(t--)
    {
        int place = 0;
        int flag = -1;
        int len = 0;
        scanf("%s", s);
        memset(ss, 0, sizeof(ss));
        strncpy(ss, s, 1);
        //printf("\n");
        len = strlen(s);
        while(place < strlen(s))
        {
            flag = macth_string(ss, s, place, strlen(ss));
            if(flag) place += strlen(ss);   //this could merge into macth_string; don't merge!
            else
            {
                strncpy(ss, s, strlen(ss)+1);
                place = strlen(ss);
            }
        }
        //output ss and strlen(ss)
        printf("%ld\n", strlen(ss));
        if(t)
            printf("\n");
    }
    return 0;
}

int macth_string(char* ss, char* s, int place, int ss_len)
{
    int m_flag = 1;
    //macthing from tag place, if failure return 0
    for(int i=0; i<ss_len; i++)
    {
        if(ss[i] != s[place+i])
        {
            m_flag = 0;
            break;
        }
    }
    //if matching success, return 1
    return m_flag;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值