ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Periods of Words

2022-04-26 01:34:21  阅读:189  来源: 互联网

标签:ba 前缀 len Periods Words 字符串 长度 周期


题目描述

对于一个仅含小写字母的字符串 a,p 为 a 的前缀且 p≠a,那么我们称 p 为 a 的 proper 前缀。

规定字符串 Q(可以是空串)表示 a 的周期,当且仅当 Q 是 a 的 proper 前缀且 a 是 Q+Q 的前缀。

例如 ab 是 abab 的一个周期,因为 ab 是 abab 的 proper 前缀,且 abab 是 ab+ab 的前缀。

求给定字符串所有前缀的最大周期长度之和。

输入格式

In the first line of the standard input there is one integer kk (1\le k\le 1\ 000\ 0001≤k≤1 000 000) - the length of the string. In the following line a sequence of exactly kk lower-case letters of the English alphabet is written - the string.

输出格式

In the first and only line of the standard output your programme should write an integer - the sum of lengths of maximum periods of all prefixes of the string given in the input.

输入输出样例

输入 #1
8
babababa
输出 #1
24

 

分析:

找出所给字符串所有前缀子串的最长周期的长度之和。

以babababa为例,每个前缀字串的最长周期分别为:
b 0
ba 0
bab ba                【b】
baba ba              【ba】
babab baba         【b】
bababa baba        【ba】
bababab bababa   【b】
babababa bababa 【ba】
所以只需求出它的最短相同前后缀的长度,再用这个子串的长度减去这个最短相同前后缀的长度。

代码

#include <iostream>
using namespace std;

int main()
{
    int len,n = 0,b[1000005]; //字符串长度len,相同前后缀长度n,记录前缀子串最长周期的数组b
    scanf("%d",&len);
    char a[1000005]; //存放字符串的数组a
    scanf("%s",a);
    b[0]=0;
    b[1]=0; //前两个前缀子串的周期都为0
    for (int i = 1;i < len;i++)
    {
        while (n>0 && a[i]!=a[n])
        {
            n = b[n];
        }
        if (a[i] == a[n]) n++;
        b[i+1] = n;
    }
    long long ans = 0; //最长周期之和ans
    for (int i = 1;i <= len;i++)
    {
        n = i;
        while (b[n]!=0) n = b[n];
        if (b[i]!=0) b[i] = n;
        ans = ans + i - n; //子串长度-相同前后缀长度
    }
    cout << ans; //或printf("%lld",ans);
  return 0;
}

 

标签:ba,前缀,len,Periods,Words,字符串,长度,周期
来源: https://www.cnblogs.com/branthx/p/16193085.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有