Palindromes
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 1062 Accepted Submission(s): 460
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
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string s;
while(cin>>s)
{
int p,i,half,left,right,count;
i=s.size();
count=0;
//从左到右钉住最后一个
for(int p=0;p<i-1;p++)
{
half=((i-1)-p)/2;
if(((i-1)-p)%2==0) //奇数
{
left=p+half-1;
right=p+half+1;
}
else //偶数
{
left=p+half;
right=p+half+1;
}
while(p<=left)
{
if(s[left]==s[right])
{
count++;
left--;
right++;
}
else break;
}
}
for(int p=i-2;p>=1;p--)
{
half=p/2;
if(p%2==0)
{
left=half-1;
right=half+1;
}
else
{
left=half;
right=half+1;
}
while(left>=0)
{
if(s[left]==s[right])
{
count++;
left--;
right++;
}
else
break;
}
}
cout<<count+i<<endl;
}
return 0;
}