My simple c++ solution


  • 7
    K
    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);
        
    }
    

    };


  • 0
    H

    FABULOUS!!!!!!!!!!!!!!


  • 0
    F

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


  • 0
    L

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


  • 1
    X

    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]. 
    

    Here is the newest code:

    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.


  • 0
    F

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

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

Log in to reply
 

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