poj------2406 Power Strings

本文介绍了一个字符串处理问题,即寻找给定字符串的最大重复次数n,使得原字符串可以表示为某个子串a重复n次构成。文章提供了一种利用KMP算法中的next数组来解决该问题的方法,并附上了Java实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A - Power Strings 难度:☆☆
Time Limit:3000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u
Submit  Status  Practice  POJ 2406

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

Hint

This problem has huge input, use scanf instead of cin to avoid time limit exceed.

 from http://poj.org/problem?id=2406

考察kmp算法中的next数组....

next的两种表示方法,第一种是前缀next[]数组...

while(i<len)
{
    if(-1==j||ss[i]==ss[j])
    {
        i++;
        j++;
        next[i]=j; 
    }
    else  j=next[j];
}

 

另种表示方法文为:

while(i<len)
{
   if(j==-1||ss[i]==s[j])
 {
     i++:
     j++;
     if(ss[i]==ss[j])
    {
         next[i]=next[j];
    } 
   else  next[i]=j;
 }
  else  j=next[j];
}

 

 这道题是考察有多少个重复的最大n所以我们不妨看他的回溯长度len_D=len(已经匹配的位置) --next[len](对应部分的匹配值);

 

Java代码:

  

 1 //package dek0;
 2 
 3 import java.util.Scanner;
 4 
 5 public class Main {    
 6     
 7     public static void main(String args[])
 8     {
 9         Scanner  reader = new Scanner(System.in);
10         String ss="";
11         while(reader.hasNext())    
12         {
13            ss=reader.next();
14            if(ss.charAt(0)=='.') break;
15            int len=ss.length();
16            int next[]=new int [len+1];
17                next[0]=-1;
18            int i=0,j=-1;
19            while(i<len)
20            {
21                if(j==-1||ss.charAt(i)==ss.charAt(j))
22                {
23                  i++;
24                  j++;
25             /*     if(ss.charAt(i)==ss.charAt(j))
26                          next[i]=next[j];
27                  else      next[i]=j;*/
28                  next[i]=j;
29                }
30                else  j=next[j];
31            }
32            if(len%(len-next[len])==0)
33              System.out.println(len/(len-next[len]));
34            else
35                System.out.println(1);
36         }
37     }
38 }

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值