4ms soln. It's easy, not as difficult as I expected.


  • 0

    Firstly, I was thinking why it mentions the length of 1000, so I never thought the brute force method got the best results.

    class Solution {
    public:
    string longestPalindrome(string s) {
        size_t size = s.length();
        if(size < 2){
            return s;
        }
        string res;
        size_t eStart = 0;
        size_t eEnd = 0;
        int i = 0;
        int j = 0;
        for( ; 2*size-eStart-eEnd > res.length(); eStart = eEnd){
            while(s[eStart] == s[eEnd]){
                ++eEnd;
            }
            i = eStart-1;
            j = eEnd;
            for(; i>=0 && j<size; --i, ++j){
                if(s[i] != s[j]){
                    break;
                }
            }
            size_t nSize = j-1-i;
            if(nSize > res.length()){
                res = s.substr(i+1, nSize);
            }
        }
        return res;
    }};

Log in to reply
 

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