9 Lines C++ Solution(With Detailed Explanation). Coding is Art!


  • 2
    class Solution {
    public:
        string longestPalindrome(string s) {
            if (s.length() <= 1) return s;
    
            int max_length = -1, l, r, res;
            
            for(int center = 0; center < s.length(); center++){
                // Skip duplicate,  reduce the running time to 8 ms
                if (center > 1 && s[center] == s[center-1]) continue;
                
                l = r = center;
                
                // Move right pointer to the last duplicate bit 
                while(r + 1< s.length() && s[r + 1] == s[center]) r++; 
                while(l > 0 && r < s.length() - 1 && s[l-1] == s[r+1]) l--, r++;
                
                // Update result
                if(r - l> max_length)  max_length = r - l,  res = l;
            }
            return s.substr(res, max_length + 1);
        }
    };
    

Log in to reply
 

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