2009年3月8日 星期日

Q10298: Power String

// Run time: 0.140
#include <stdio.h>
#include <string.h>
const int N = 1000000;
char str[N+1];
int calculate(int length);

int main()
{
int length;
int n;

while (gets(str) && str[0] != '.')
{
length = strlen(str);
n = calculate(length);
printf("%d\n", n);
}
return 0;
}

int calculate(int length)
{
int i, j, k;
int len;
bool s;
char tmp[length+1];

for ( i = 0; i < length; i++)
{
if (!(length%(i+1)))
{
s = true;

// assign substring to tmp
for ( j = 0; j <= i; j++)
tmp[j] = str[j];
tmp[j] = '\0';

// tmp's length
len = j;

// look for other substring
for ( j = len; j < length; j+= len)
{
for ( k = 0; k < len; k++)
{
if (tmp[k] != str[j+k])
{
s = false;
break;
}
}

if (!s) break;
}

if (s) break;
}

}

// if i == length, it means substring is equal to str
return (i == length) ? 1 : length/(i+1);

}

沒有留言: