Leetcode Longest Palindromic Substring problem solution in C++

Feb 11, 2023

In the Leetcode Longest Palindromic Substring problem solution in C++ programming Given a string s, return the longest palindromic substring in s.

Leetcode Longest Palindromic Substring problem solution in C++ programming

``````class Solution {
public:
string longestPalindrome(string s) {
int n=s.length();

if(s.length()==0){
return "";
}

string ans;
int max_len=0;

for(int i=0;i<n;i++){
//here we check at every index if we can found the palindrome with middle index as i
//now two cases arrives palindrome with even length
//palindrome with odd length
int j=0 ;
while(i-j>=0&&i+j<n&&s[i-j]==s[i+j])
{//this loop will handle palindrome with odd length

if(max_len<2*j+1)
{
max_len=2*j+1;
ans=s.substr(i-j,2*j+1);

}
j++;
}
j=1;
while(i-j+1>=0&&i+j<n&&s[i-j+1]==s[i+j])
{//this loop will handle palindrome with even length
int curr_len=2*j;
if(max_len<curr_len)
{
max_len=curr_len;
ans=s.substr(i-j+1,2*j);
}
j++;
}
}
return ans;
}
};``````

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.