题目描述

给你一个字符串 s,找到 s 中最长的回文子串。
示例 1:

  1. 输入:s = "babad"
  2. 输出:"bab"
  3. 解释:"aba" 同样是符合题意的答案。

示例 2:

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

示例 3:

输入:s = "a"
输出:"a"

示例 4:

输入:s = "ac"
输出:"a"

提示:

  1. 1 <= s.length <= 1000
  2. s 仅由数字和英文字母(大写和/或小写)组成

    分析

    从中间向两侧增长,以中心位置作为对称轴分别向左右进行增长判断。
    5 最长回文字串 - 图1
    从中间开始向两侧查找最大的对称的边界,时间复杂度5 最长回文字串 - 图2

    答案

    class Solution {
     pair<int, int> expand(const string& s, int left, int right) {
         while (left >= 0 && right < s.size() && s[left] == s[right]) {
             --left;
             ++right;
         }
         return {left + 1, right - 1};
     }
    public:
     string longestPalindrome(string s) {
         int start = 0;
         int end   = 0;
         for (int i = 0; i < s.size(); i++) {
             auto t1 = expand(s, i, i);
             auto t2 = expand(s, i, i + 1);
             if (t1.second - t1.first > end - start) {
                 end   = t1.second;
                 start = t1.first;
             }
             if (t2.second - t2.first > end - start) {
                 end   = t2.second;
                 start = t2.first;
             }
         }
         return s.substr(start, end - start + 1);
     }
    };