Power Strings
Description
Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "abcdef". If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = "" (the empty string) and a^(n+1) = a*(a^n).
Input
Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.
Output
For each s you should print the largest n such that s = a^n for some string a.
Sample Input
abcd aaaa ababab .
Sample Output
1 4 3
题意
给你一个字符串,找出他最多是重复了几次。比如aaaa就是以a重复了4次,abab就是以ab重复了2次
解题思路
首先找到周期,然后再判断重复了几次。
找周期的时候引用两个下标 i,j 。i-j表示周期的长度,j表示上一个周期内某个元素,i表示这个元素对应的下一个周期中的元素。
i初始为0,j初始为-1。
例如
字符串a为 ababa
数组b存的是每个字符的重复次数,初始为零,最终答案就是最后一个字符重复次数加1即可
0 | 1 | 2 | 3 | 4 |
a | b | a | b | a |
当i=1指向b,j=0指向a时,二者不相等 ----->(说明周期找的不对,重新找) j重新指向头,i后移一个单位
此时i=2指向a,j=0指向a,二者相等 ------>b[i]=b[j]+1]=1 i,j分别后移一个单位,周期为2
此时i=3指向b,j=1指向b,二者相等 ------>b[i]=b[j]+1] =1 i,j分别后移一个单位,周期为2
此时i=4指向a,j=2指向a,二者相等------>b[i]=b[j]+1] =2 i,j分别后移一个单位,周期为2
此时i=5指向结束符,j=3指向b,二者不相等 并且字符长度为5不能整除周期2 ----->b[ 0~i ] =0,(循环次数清零)
代码
#include <cstring>
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <queue>
#define INF 0x3f3f3f3f
const int maxn=50100;
using namespace std;
char s[1000000];
int b[1000000];
int main()
{
while(scanf("%s",s) && s[0]!='.')
{
memset(b,0,sizeof(b));
int j=-1,i=0;
int len=strlen(s);
while(i<len)
{
i++;j++;
if(s[i]==s[j])
{
b[i]=b[j]+1;
}
else//周期不对就重新找
{
if(i>=len)
if(len%(i-j)==0)
break;
j=-1;
for(int k=0;k<=i;++k)
b[k]=0;
}
}
printf("%d\n",b[len-1]+1);
}
return 0;
}