problem 5

This commit is contained in:
Buduf 2022-04-14 13:35:30 +02:00
parent 4fd9dbe8da
commit 8e567c7789

View File

@ -0,0 +1,40 @@
#include <string>
using namespace std;
class Solution
{
public:
string longestPalindrome(string s)
{
int max{};
int index{};
for (int i = 0; i < s.length(); i++)
{
int j = 0;
while (i - j >= 0 && i + j < s.length() && s[i - j] == s[i + j])
{
j++;
}
if (j * 2 - 1 > max)
{
max = j * 2 - 1;
index = i;
}
j = 0;
while (i - j >= 0 && i + j + 1 < s.length() && s[i - j] == s[i + j + 1])
{
j++;
}
if (j * 2 > max)
{
max = j * 2;
index = i;
}
}
if (max % 2 == 0)
{
return s.substr(index - max / 2 + 1, max);
}
return s.substr(index - max / 2, max);
}
};