fansluck
fansluck
Apr 02, 2023 23:35
C
Created with Highcharts 9.3.3
Runtime6 ms
Beats
90.86%
Created with Highcharts 9.3.3
Memory5.9 MB
Beats
91.12%
Click the distribution chart to view more details
0/5
#include <string.h>

char *longestPalindrome(char *s)
{
    short mlidx = 0, mridx = 0, lidx = 0, ridx = 0;
    short length = strlen(s);

    if (length <= 1)
        return s;
    if (length == 2)
        return s[0] == s[1] ? s : s + 1;

    for (int i = 1; i < length - 1; i++)
    {
        lidx = ridx = i;
        while (lidx > 0 && ridx < length - 1 && s[lidx - 1] == s[ridx + 1])
        {
            lidx--;
            ridx++;
        }
        if (ridx - lidx > mridx - mlidx)
        {
            mridx = ridx;
            mlidx = lidx;
        }
    }
    if (mlidx == mridx)
    {
        if (s[0] == s[1])
        {
            mlidx = 0;
            mridx = 1;
        }
        else if (s[length - 2] == s[length - 1])
        {
            mlidx = length - 2;
            mridx = length - 1;
        }
    }
    if (length > 3)
    {
        for (int i = 1; i < length - 2; i++)
        {
            if (s[i] == s[i + 1])
            {
                lidx = i;
                ridx = i + 1;
                while (lidx > 0 && ridx < length - 1 && s[lidx - 1] == s[ridx + 1])
                {
                    lidx--;
                    ridx++;
                }
            }
            if (ridx - lidx > mridx - mlidx)
            {
                mridx = ridx;
                mlidx = lidx;
            }
        }
    }

    s[mridx + 1] = '\0';
    return s + mlidx;
}