利用回文的特点进行计算,复杂度O(nlogn) #include<iostream> #include <string.h> //#include <set> using namespace std; char a[5002]; int cal(int u, int even, int len) { int sum = 1; int l=u-1, r; if(even == 0) r=u+1; else r=u+2; while (l>=0 && r<len) { if(a[l--] == a[r++]) ++sum; else break; } return sum; } int main() { int i, j, sum; while (scanf("%s", a) != EOF) { sum = 0; int len = strlen(a); for (i=0; i<len; ++i) { sum += cal(i, 0, len); if(i!=len-1 && a[i]==a[i+1]) sum += cal(i, 1, len); } printf("%d/n", sum); } return 0; }