题目描述
You are given a palindromic string ss of length nn .
You have to count the number of indices ii (1 \le i \le n)(1≤i≤n) such that the string after removing s_isi from ss still remains a palindrome.
For example, consider ss = "aba"
- If we remove s_1s1 from ss , the string becomes "ba" which is not a palindrome.
- If we remove s_2s2 from ss , the string becomes "aa" which is a palindrome.
- If we remove s_3s3 from ss , the string becomes "ab" which is not a palindrome.
A palindrome is a string that reads the same backward as forward. For example, "abba", "a", "fef" are palindromes whereas "codeforces", "acd", "xy" are not.
输入格式
The input consists of multiple test cases. The first line of the input contains a single integer tt (1 \leq t \leq 10^3)(1≤t≤103) — the number of test cases. Description of the test cases follows.
The first line of each testcase contains a single integer nn (2 \leq n \leq 10^5)(2≤n≤105) — the length of string ss .
The second line of each test case contains a string ss consisting of lowercase English letters. It is guaranteed that ss is a palindrome.
It is guaranteed that sum of nn over all test cases does not exceed 2 \cdot 10^52⋅105 .
输出格式
For each test case, output a single integer — the number of indices ii (1 \le i \le n)(1≤i≤n) such that the string after removing s_isi from ss still remains a palindrome.
题意翻译
题目描述
给定一个回文字符串 ss ,它的长度为 nn (2 \leq n \leq 10^5)(2≤n≤105) ,问一共有多少种方式使它去掉一个字符后仍是回文字符串。
输入格式
共有 tt (1 \leq t \leq 10^3)(1≤t≤103) 组数据,对于每组数据,先输入字符串的长度 nn ,再输入回文字符串 ss 。
输出格式
对于每组数据,输出一共有多少种方式使输入的字符串去掉一个字符后仍是回文字符串。
数据范围
数据保证所有的 nn 之和不超过 2 \cdot 10^52⋅105 。
输入输出样例
输入 #1复制
3 3 aba 8 acaaaaca 2 dd输出 #1复制
1 4 2说明/提示
The first test case is described in the statement.
In the second test case, the indices ii that result in palindrome after removing s_isi are 3, 4, 5, 63,4,5,6 . Hence the answer is 44 .
In the third test case, removal of any of the indices results in "d" which is a palindrome. Hence the answer is 22 .
1.这个题目是一个很简单的贪心算法题目,我们需要找到贪心规则。
2.我们不难发现,删去一个能保持原来的回文,我们只能从中间删除,而且必须是中间那一段是连续相同的字符。
所以我们从中间开始,我们会发现,因为给我们的是回文字符串,所有中间连续是对称的。
3.我们可以设置俩个哨兵,这个时候要考虑情况,如果是奇数,我们把哨兵i,j分别等于中间减一和中间加一的位置,往前后走,如果是偶数,就是一个是中间减一和中间的位置往前后走,好事成双,每次都可以加2。
4.走的时候,要判断是否和中间的数相等。
献上代码
#include<stdio.h>
#define N 100010
int res[1010];
char s[N];
int slove(char a[],int n)
{
int i,j,s=0,mid;
mid=n/2;
if(n%2==1)
{
i=mid-1;j=mid+1;s=1;
}
else
{
i=mid-1;j=mid;
}
while(i>=0&&j<n)
{
if(a[i]==a[j]&&a[j]==a[mid])
{
i--;j++;s+=2;
}
else if(a[i]==a[mid])
{
i--;
s++;
}
else if(a[j]==a[mid])
{
j++;
s++;
}
else
{
break;
}
}
return s;
}
int main()
{
int t,i,j,n;
scanf("%d\n",&t);
for(i=0;i<t;i++)
{
scanf("%d\n",&n);
scanf("%s",s);
res[i]=slove(s,n);
}
for(i=0;i<t;i++)
{
printf("%d\n",res[i]);
}
return 0;
}
Accepted!!!