Featured image of post 5.Longest Palindromic Substring

5.Longest Palindromic Substring

最长回文子串

目录

最长回文子串

  给出一个字符串 $s$,返回其最长的回文子串。 例1:

输入:s = "babad"
输出:"bab"
解析:"aba" 也是一个有效的答案。

例2:

输入:s = "cbbd"
输出:"bb"

约束条件:

$$\begin{aligned} 1 <= s.length <= 1000& \\ s 仅仅包含数字和英文字母& \end{aligned}$$

一般来说,这道题首先想到的教科书式解法是动态规划,这里解法使用early-stop规则,内存占用也降低:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#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;
}
C

提交截图(提交时,非现在状态)


完整信息点击此连接查看