problem 5
This commit is contained in:
parent
4fd9dbe8da
commit
8e567c7789
40
LongestPalindromicSubstring.cpp
Normal file
40
LongestPalindromicSubstring.cpp
Normal 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);
|
||||||
|
}
|
||||||
|
};
|
||||||
Loading…
x
Reference in New Issue
Block a user