My simple c++ solution

• ``````class Solution {
public:
string longestPalindrome(string s) {
if(s.length()==0||s.length()==1)return s;
string max=""+s[0];
for(int i=0;i< s.length()-1; i++){
string first=helper(s, i, i);
if(first.length() > max.length())max=first;

string second=helper(s, i, i+1);
if(second.length() > max.length())max=second;
}
return max;
}

string helper(string s, int left, int right){
while(left >=0 && right <s.length() && s[right]==s[left]){
left--;
right++;
}
return s.substr(left+1, right-1-left);

}
``````

};

• FABULOUS!!!!!!!!!!!!!!

• The solution is very clear and speaks for itself. Thank you!!

• It fails with "bb" for me on LeetCode but not on an IDE.

• Re: My simple c++ solution
The solution failes with "bb" on LeetCode not on an IDE. This is because
string intialization

``````string max=""+s[0].
``````

``````string longestPalindrome(string s) {
if(s.length()==0||s.length()==1)return s;
string max("");
for(int i=0;i< int(s.length())-1; i++){
string first=helper(s, i, i); // The center is s[i]
if(first.length() > max.length())max=first;

string second=helper(s, i, i+1); // The center is s[i][i]
if(second.length() > max.length())max=second;
}
return max;
}

string helper(string s, int left, int right){
while(left >=0 && right <int(s.length()) && s[right]==s[left]){
left--;
right++;
}
return s.substr(left+1, right-1-left);
}
``````

However, this one is not the fastest. It will elaborate all the palindromic substrings and may have redundant counting on some palindromic substrings.

• This is a good idea!
If changing the condition, use less runtime.

``````for(int i = 0; i < (n - maxSubLen/2); i++)
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.