基礎題,將原字符串中每一個字符作爲迴文子串的中心點,按照子串長度爲奇數和偶數向兩邊擴展即可。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
while (cin >> s)
{
int len = s.size();
int ans = 0;
int l, r;
for (int i = 0; i < len; i++)
{
//子串長度爲奇數
l = i - 1;
r = i + 1;
while (l >= 0 && r < len && s[l] == s[r])
{
--l;
++r;
++ans;
}
//子串長度爲偶數
l = i;
r = i + 1;
while (l >= 0 && r < len && s[l] == s[r])
{
--l;
++r;
++ans;
}
}
cout << ans + len << endl;
}
return 0;
}
繼續加油。