5. Longest Palindromic Substring -- Could any one tell me why time exceed?


  • 0
    X

    class Solution {
    public:
    int size;
    string glo_s;
    string longestPalindrome1(string s) {
    size = s.size();
    glo_s = s;
    int Max = 0;
    string res;

        for (int i = 0; i < size; i++)
        {
            string tmp = palin(i);
            if(tmp.size() > Max)
            {
                Max = tmp.size();
                res = tmp;
            }
        }
        return res;
    }
    string palin(int x)
    {
        string str1 = odd(x);
        string str2 = even(x);
        if(str1.size() > str2.size())
            return str1;
        else
            return str2;
    }
    string odd(int x)
    {
        string str;
        str += glo_s[x];
        for (int i = 1; i <= min(x, size-1-x); i++)
        {
            if (glo_s[x-i] == glo_s[x+i])
                str = glo_s[x-i] + str + glo_s[x+i];
            else
                break;
        }
        return str;
    }
    string even(int x)
    {
        string str;
        for (int i = 0; i <= min(x-1, size-1-x); i++)
        {
            if(glo_s[x-1-i] == glo_s[x+i])
                str = glo_s[x-1-i] + str + glo_s[x+i];
            else
                break;
        }
    

    };
    return str;
    }


Log in to reply
 

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