A C++ recursive solution, even though there is a Time Limit Exceeded problem


  • 0
    S

    Just provide a different idea. The code passes 30/94 cases and encounter a time limit exceeded problem.
    '''
    class Solution {
    public:
    string longestPalindrome(string s) {
    if(s.empty()) return "";
    if(s.size()==1) return s;
    string str;
    int i = 0;
    int j = s.length()-1;
    while(i<j){
    if(s[i]==s[j]){
    str.insert(str.length()/2,2,s[i]);
    i++; j--;
    }
    else
    {
    string str1 = longestPalindrome(s.substr(1));
    string str2 = longestPalindrome(s.substr(0,s.length()-1));
    if(str1.length()>str2.length()) str = str1;
    else str = str2;
    break;
    }
    }
    if(i==j) str.insert(str.length()/2,1,s[i]);
    return str;
    }
    };
    '''


Log in to reply
 

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