欢迎来到王正伟的博客

返回顶部

5:最长回文子串(C++)

题目地址https://leetcode-cn.com/problems/longest-palindromic-substring/

题目描述

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

题目示例

示例 1:

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

输入:s = "cbbd"
输出:"bb"
示例 3:

输入:s = "a"
输出:"a"
示例 4:

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

解题思路

思路1:暴力遍历,超时。暴力遍历所有可能的结果,回文子串str与其反转结果temp应相同,即str==temp。

思路2:双指针+中心扩散方法。具体思路分两步:

Step1:确定回文串;

Step2:中心向两边扩散

  • 一个元素作为中心点(三个元素作为中心点可由一个元素左右各扩展一个元素得到)
  • 两个元素作为中心点(四个元素作为中心点可由两个元素左右各扩展一个元素得到)

程序源码

思路1

class Solution {
public:
    string longestPalindrome(string s) {
        if(s.size() < 2) return s;
        string res = ""; //存放结果
        string str = ""; //存放子串
        for(int i = 0; i < s.size(); i++)
        {
            for(int j = i; j < s.size(); j++)
            {
                str += s[j];
                string temp = str; //存放子串反转结果
                std::reverse(temp.begin(), temp.end());
                if(str == temp)
                {
                    res = res.size() > temp.size() ? res : temp;
                }
            }
            str = "";
        }
        return res;
    }
};

 思路2:

class Solution {
    int left = 0, right = 0;
    int maxLength = 0; 
public:
    string longestPalindrome(string s) {
        if(s.size() < 2) return s;
        for(int i = 0; i < s.size(); i++)
        {
            extend(s, i, i, s.size()); //以i为中心点扩展
            extend(s, i, i + 1, s.size()); //以i和i+1为中心点扩展
        }
        return s.substr(left, maxLength);
    }
    void extend(string &s, int i, int j, int n)
    {
        while(i >= 0 && j < n && s[i] == s[j])
        {
            if(j - i + 1 > maxLength)
            {
                left = i;
                right = j;
                maxLength = j - i + 1;
            }
            i--;
            j++;
        }
    }
};

参考文章

https://leetcode-cn.com/problems/longest-palindromic-substring/solution/5-zui-chang-hui-wen-zi-chuan-dong-tai-gu-jy7k/

posted @ 2021-02-04 13:12  Mr.King~  阅读(556)  评论(0编辑  收藏  举报