longest palindromic substring in c++

  • Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring ??

class Solution {
string expandAroundCenter(string s, int c1, int c2) {
int l = c1, r = c2;
int n = s.length();
while (l >= 0 && r <= n-1 && s[l] == s[r]) {
return s.substr(l+1, r-l-1);

string longestPalindrome(string s) {
int n =s.length();
if (n == 0) return “”;
string longest=s.substr(0,1);
for(int i=0 ; i<n ;i++)
string p1 = expandAroundCenter(s, i, i);
if (p1.length() > longest.length())
longest = p1;

string p2 = expandAroundCenter(s, i, i+1);
if (p2.length() > longest.length())
longest = p2;
return longest;

Runtime : 280 ms

Resolving technical problems:

Solve your technical problems instantly

We provide Remote Technical Support from Monday to Sunday, 7:00PM to 1:00 AM

Mail your problem details at [email protected] along with your mobile numberand we will give you a call for further details. We usually attend your problems within 60 minutes and solve it in maximum 2 days.