Palindromes
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 1526 Accepted Submission(s): 722
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
题目大意:让求回文字符串的个数。
分析:由样例可知,要加上字符串的长度,因为每个字符也是回文字符串。
也是够了,看了别人的思路,才会用string来实现
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
while(cin>>str)
{
int sum=0;
for(int i=1;i<str.size()-1;i++)//以一个字符对称的
{
int h=i-1,k=i+1;
while(h>=0&&k<=str.size())
{
if(str[h]==str[k])
{
sum++;
h--;
k++;
}
else
break;
}
}
for(int i=0;i<str.size()-1;i++)//以两个字符对称的
{
int h=i,k=i+1;
if(str[h]==str[k])
{
while(h>=0&&k<=str.size())
{
if(str[h]==str[k])//多比较了一次,可以完善,将sum++放在前面考虑一次
{
sum++;
h--;
k++;
}
else
break;
}
}
}
cout<<sum+str.size()<<endl;
}
}