Share c++ O(N^2)solution


  • 0
    string longestPalindrome(string s) 
    {
        string result;
        
        for (int i = 0; i < s.size(); i++)
        {
            int j = i - 1;
            while ((j >= 0) && (s[j] == s[i])) 
                j--;
            
            int k = i + 1;
            while ((k < s.size()) && (s[k] == s[i])) 
                k++;
            
            while ((j >= 0) && (k < s.size()) && (s[j] == s[k]))
                j--, k++;
            j++, k--;
            
            if (k - j + 1 > result.size())
                result = s.substr(j, k - j + 1);
        }
        
        return result;
    }

Log in to reply
 

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