Ugly but easy understand 3ms C++ solution


  • 0
    H
    class Solution {
    public:
        string longestPalindrome(string s) {
            
            int len = s.size();
            int maxLeft = 0, maxRight = 0, maxLen = 0, curLen = 0;
            int preIdx, postIdx;
            
            for (int idx = 0; idx < len; idx++)
            {
                preIdx = idx - 1;
                postIdx = idx + 1;
                
                // scan the repeatable chars
                while (s[postIdx] == s[idx] && postIdx < len)
                {
                    postIdx++;
                }
                
                idx = postIdx - 1;
    
                // regular scan
                while (preIdx >= 0 && postIdx <len)
                {
                    if (s[preIdx] == s[postIdx])
                    {
                        preIdx--;
                        postIdx++;
                        continue;
                    }
                    else
                    {
                        break;
                    }
                    
                }
    
                preIdx++;
                postIdx--;
                
                curLen =  postIdx - preIdx + 1;
                
                if ( curLen > maxLen)
                {
                    maxLen = curLen;
                    maxLeft = preIdx;
                    maxRight = postIdx;
                }
            }
            
            return s.substr(maxLeft,maxLen);
        }
    };
    

Log in to reply
 

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