C++ 6ms 8 lines solution with comments


  • 2
    string longestPalindrome(string s) {
            int start = 0, len = 0;                               //start, len: answer's start position and length
            
            for (int mid = 0, l = 0, r = 0; len / 2 < s.length() - mid; l = mid, r = mid) {
                while (r + 1 < s.length() && s[r] == s[r + 1]) { r++; }                         // skip duplicates
                mid = r + 1;
                
                while (0 <= l - 1 && r + 1 < s.length() && s[l - 1] == s[r + 1]) { l--, r++; }  // expand palindromic substring
                if (len < r - l + 1) { start = l, len = r - l + 1; }                            // update candidate
            }
            
            return s.substr(start, len);
    }
    

  • 0
    N

    I like this solution! Simple, elegant and fast!


Log in to reply
 

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