先整理各路大神的题解 Orz,以后再埋坑

 

Description

求一个串中包含几个回文串。

Input

输入一个字符串S

Output

包含的回文串的个数.

思路一:

用马拉车求出预处理后以每个字母处的回文半径P[i],遍历一遍,ans=ans+P[i]/2,最终ans就是答案

答案是以每一位为中心的回文串长度/2的和,(如果添加字符则为回文半径长度/2。)

不能理解的话,可以看下这个

# a # a # b # a # a #

1   2  3  2 1  6 1  2  3  2  1

数字对应于每一个位置的回文半径

.(实际上减去1才是,但是计算的时候要加上1,所以代码里面直接用了这个.)

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<iostream>
 4 #include<cstring>
 5 #define R register
 6 
 7 using namespace std;
 8 
 9 const int maxn=1008;
10 
11 char ch[maxn];
12 char s[maxn<<2];
13 int len,RL[maxn<<2],MaxRight,center,ans;
14 int main()
15 {
16     scanf("%s",ch);
17     len=strlen(ch);
18     for(R int i=0;i<len;i++)s[2*i+1]=ch[i];
19     len=2*len+1;
20     for(R int i=0;i<len;i++)
21     {
22         if(i<=MaxRight)
23             RL[i]=min(RL[2*center-i],MaxRight-i);
24         else RL[i]=1;
25         while(s[i-RL[i]]==s[i+RL[i]] and i-RL[i]>=0 and i+RL[i]<len)
26             RL[i]++;
27         if(i+RL[i]-1>MaxRight)
28             MaxRight=i+RL[i]-1,center=i;
29     }
30     for(R int i=0;i<len;i++)ans+=RL[i]/2;
31     printf("%d",ans);
32 }
View Code

相关文章:

  • 2021-09-20
  • 2022-02-27
  • 2021-12-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-08
猜你喜欢
  • 2022-12-23
  • 2021-12-11
  • 2021-06-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-27
相关资源
相似解决方案