求串回文数
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
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.
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.
Output
A single line with the number of palindrome substrings for each case.
Sample Input
aba
aa
Sample Output
4
3
求串回文数,标记着一种思想
这道理刚看完我就断定如果用一般的方法一定会TLE
有人说用DP,但我的DP内功并不是很深厚,于是暂时放弃这种方法
这题的题意很容易理解,但关键是怎么样做到不要超时
关键中的关键便是如何不要重复计算和做一些无谓的比较
于是不用考虑要去写一个什么判段回文的函数了
理解下回文的本质吧,如果n个字符是回文,那么里面的n-2个字符也是回文
用这样的思想便可以很好的避免重算
好像被我说复杂了~~~
AC代码:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int i,j,k,slen,p,q,sum;
char str[5001];
while (scanf("%s",&str)!=EOF)
{
sum = 0;
slen = strlen (str);
for (i=0;i<slen;i++) //遍历所有字符串
{
for (j=0;j<=1;j++) //对一个字符两种情况的搜索
{
p = i - j; //左边数
q = i + 1; //右边数
while (p>=0 && q<slen)
{
if (str[p] == str[q])
{
sum++;
p--; //下一次尝试
q++; //两边各移一位
}
else
break;
}
}
}
printf("%d/n",slen+sum);
}
return 0;
}