zoukankan      html  css  js  c++  java
  • POJ2406A- Power Strings

    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.

    思路:题意是让你求能构成循环的最多次数,关键是利用next数组的构建,其是KMP算法的精髓。

    对于代码中i-next[i]代表了字符串最小前缀且满足能不但的复制得到

    原字符串;len%(i-next[i])==0时代表字符串刚刚是子串的整数倍;

    若len%(i-next[i])==0匹配时每一次移动的距离i-next[i]是相等的,若不等则只有最后一次不等;

    #include <iostream>
    #include<cstring>
    #include<cstdio>
    using namespace std;
    
    char str[1000010],pat[1000010];//pat为模式串,str为主串
    int Next[1000010]; //Next[x]下标x表示匹配失败处字符下标
    //模式串pat的前缀与x位置的后缀的最大匹配字符个数-1
    void GetNext(char *pat)
    {
        int LenPat = strlen(pat);
        int i = 0,j = -1;
        Next[0] = -1;
        while(i < LenPat)
        {
            if(j == -1 || pat[i] == pat[j])
            {
                i++,j++;
                Next[i] = j;
            }
            else
                j = Next[j];
        }
       
    }
    /*      
    int KMP()//返回模式串pat在str中第一次出现的位置
    {
        int LenStr = strlen(str);
        int LenPat = strlen(pat);
        //GetNext(pat);
        int i = 0,j = 0;
        int ans = 0;//计算模式串在主串匹配次数
        while(i < LenStr)
        {
            if(j == -1 || str[i] == pat[j])
                i++,j++;
            else
                j = Next[j];
            if(j == LenPat)
            {
                //ans++; ans存放匹配次数,去掉return,最后返回ans
                return i - LenPat + 1;
            }
        }
        return -1;//没找到匹配位置
        //return ans;//返回匹配次数。
    } */
    int main()
    {
        while(scanf("%s",str))
        {
            if(str[0]=='.')
                break;
            int len=strlen(str);
            GetNext(str);
            int k=len-Next[len];
            int ans;
            if(len%k==0)
                ans=len/k;
            else
                ans=1;
            printf("%d
    ",ans);
        }
        return 0;
    }
  • 相关阅读:
    spring 04-Spring框架依赖注入基本使用
    spring 03-Spring开发框架之控制反转
    spring 02-Maven搭建Spring开发环境
    spring 01-Spring开发框架简介
    JVM堆内存、方法区和栈内存的关系
    jvm 07-java引用类型
    jvm 06-G1收集器
    jvm 05-JVM垃圾收集策略
    jvm 04-JVM堆内存划分
    CSS书写顺序
  • 原文地址:https://www.cnblogs.com/aerer/p/9931018.html
Copyright © 2011-2022 走看看