Palindromes
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 912 Accepted Submission(s): 389
Total Submission(s): 912 Accepted Submission(s): 389
Problem Description
A regular palindrome is a string of numbers or letters that is the same forward as backward. For example, the string "ABCDEDCBA" is a palindrome because it is the same when the string is read from left to right as when the string is read from right to left.
Now give you a string S, you should count how many palindromes in any consecutive substring of S.
Now give you a string S, you should count how many palindromes in any consecutive substring of S.
Input
There are several test cases in the input. Each case contains a non-empty string which has no more than 5000 characters.
Proceed to the end of file.
Proceed to the end of file.
Output
A single line with the number of palindrome substrings for each case.
Sample Input
aba aa
Sample Output
4 3
————————————————————————————————————————————————————————
可以通过压缩来减少对相同字符的字符串的处理,可用公式n*(n+1)/2来求count
/****************************
*Name:Palindromes.c
*Tags:ACM water
*Note:可以通过压缩来减少对相同字符的字符串的处理,可用公式n*(n+1)/2来求count
****************************/
#include <stdio.h>
#include <string.h>
int main()
{
int is_p;
char str[5002], prostr[5002];
int num[5002];
int l, i, j, count, t, t1, t2;
while(scanf("%s", str) != EOF) {
t = 0;
num[0] = 1;
prostr[0] = str[0];
for(i = 1; str[i]; i++) {
if(str[i] == str[i-1]) {
num[t]++;
} else {
t++;
prostr[t] = str[i];
num[t] = 1;
}
} //压缩
l = t+1;
count = 0;
for(i = 0; i < l; i++) {
count += num[i]*(num[i]+1)/2;
}
for(i = 0; i < l; i++) {
t1 = i-1;
t2 = i+1;
if(t1 < 0 || t2 >= l) {
continue;
}
is_p = 0;
while(prostr[t1] == prostr[t2] && num[t1] == num[t2]) {
count += num[t1];
t1--;
t2++;
if(t1 < 0 || t2 >= l) {
is_p = 1;
break;
}
}
if(is_p == 0 && prostr[t1] == prostr[t2]) {
if(num[t1] < num[t2]) {
count += num[t1];
} else {
count += num[t2];
}
}
}
printf("%d\n", count);
}
return 0;
}