Share my solution in C++ 4ms


  • 0
    W

    class Solution {
    public:
    string longestPalindrome(string s) {
    string reverse = string(s);
    int i, len, start, size;

        size = s.size();
        if(size<=1) // null string or single letter
            return s;
        start = 0;
        len = 1; // at first, start from position 0 with max len = 1
        if(s[1]==s[0])
            len=2;
        for(i=0 ; i<size ; i++){
            reverse[i]=s[size-1-i];
        }
        cout<<size<<endl;
        for(i=1 ; i<size; i++){
            if(i-len>=0 && s.compare(i-len, len+1, reverse, size-i-1, len+1)==0){ // possible len -> len+1
                start = i-len;
                len = len+1;
            }
             if(i-len-1>=0 && s.compare(i-len-1, len+2, reverse, size-i-1, len+2)==0){ // possible len -> len+2
                start = i-len-1;
                len = len+2;
            }
        }
        return s.substr(start, len);
    }
    

    };


Log in to reply
 

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