C++ O(n*n) concise solution.


  • 1
    C
    string longestPalindrome(string s) {
        string res = "";
        for (unsigned int i = 0; i < s.size(); i++) {
            for (int j = 0; j < 2; j++) {
                string str = palindrome(s, i, i+j);
                if (str.size() > res.size())
                    res = str;
            }
        }
        return res;
    }
    
    string palindrome(string s, int l, int r) {
        while (l >=0 && r <s.size() && s[l]==s[r]) {
            l--; r++;
        }
        return s.substr(l+1, r-l-1);
    }

Log in to reply
 

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