[Leetcode]Longest Palindromic Substring

Posted 言何午

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode]Longest Palindromic Substring相关的知识,希望对你有一定的参考价值。

Longest Palindromic Substring 题解

原创文章,拒绝转载

题目来源:https://leetcode.com/problems/longest-palindromic-substring/description/


Description

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

Input: "cbbd"

Output: "bb"

Solution

class Solution {
private:
    int resStart;
    int resSize;
    int inSize;
    void expandPalindrome(string& s, int start, int end) {
        while (start >= 0 && end < inSize && s[start] == s[end]) {
            start--;
            end++;
        }
        start++;
        int temp = end - start;
        if (temp > resSize) {
            resSize = temp;
            resStart = start;
        }
    }
public:
    string longestPalindrome(string s) {
        inSize = s.length();
        if (inSize <= 1)
            return s;
        resStart = resSize = 0;
        for (int i = 0; i < inSize - 1; i++) {
            expandPalindrome(s, i, i); // 求奇数长度的回文子串
            expandPalindrome(s, i, i + 1); // 求偶数长度的回文子串
        }
        return s.substr(resStart, resSize);
    }
};

解题描述

这道题考察的是求一个字符串中的最长回文子串。而对每一个非空的输入串来说,其回文子串最短为1,因此可以对字符串中的每一个元素,同时向左和向右探测,直到回文子串结束,每次判断得到的子串是否是最长的即可。

以上是关于[Leetcode]Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode409. Longest Palindrome

leetcode:longest-increasing

[Leetcode]Longest Palindromic Substring

leetcode longest consecutive sequence

LeetCode Longest Increasing Subsequence

#Leetcode# 14. Longest Common Prefix