《HOT100》

《HOT100》做题记录

5.最长回文子串

🔗 给你一个字符串 s,找到 s 中最长的 回文 子串。

 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
class Solution {
    static const int N = 1e3 + 10;
    static const int p[N], b[N];
public:
    string longestPalindrome(string s) {
        // 用 manacher 算法求解
        int k = 0, n = 0;

        auto init = [&]() {
            b[k ++ ] = '$', b[k ++ ] = '#';
            for (auto c : s) {
                b[k ++ ] = c;
                b[k ++ ] = '#';
            }
            b[k ++ ] = '^';
            n = k;
        };

        init();

        auto manacher = [$]() {
            int mr = 0, mid = 0;
            for (int i = 1; i < n; i ++ ) {
                if (i < mr) p[i] = max(2 * mid - i, mr - i);
                else p[i] = 1;

                while (b[i - p[i]] == b[i + p[i]]) p[i] ++ ;
                if (i + p[i] > mr) {
                    mr = i + p[i];
                    mid = i;
                }
            }
        };

        manacher();

        // 如果只是求最长回文子串的长度,返回res即可
        int res = 0, max_i = 0;
        for (int i = 0; i < n; i ++ ) {
            if (p[i] > res) {
                res = p[i];
                max_i = i;
            }
        }

        // 如果是求具体的回文子串,需要根据最长长度截取
        int start = max_i - (res - 1);
        int end = max_i + (res - 1);
        for (int i = start; i <= end; i ++ ) {
            if (i == 0 || i == n - 1) continue;
            if (i % 2 == 0) ans.push_back(b[i]);
        }
        return ans;
    }
};
yitao 支付宝支付宝
yitao 微信微信
0%