LeetCode——005 Longest Palindromic Substring

Description

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

** Example 1: **

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

** Example 2: **

Input: "cbbd"
Output: "bb"

** Solution: **

Used in the idea of symmetry
and traversed from the beginning, for about outdiffusion for each letter, judgment is not palindromic substring
noted, spread out in two ways, first, the letter in the center is spread out, the second letter is the letter and the right end thereof outward diffusion started

class Solution {
public:
    string longestPalindrome(string s) {
        string res = "";
        for (int i = 0; i < s.length(); ++i)
        {
            help(s, i - 1, i + 1, res);//奇数类型的中心向两边扩撒
            help(s, i, i + 1, res);//偶数类型的中心向两边扩撒           
        }
        return res;
    }
    void help(const string &s, int L, int R, string &res)
    {
        while (L >= 0 && R < s.length())
        {
            if (s[L] != s[R])break;
            --L;
            ++R;
        }
        if (R - L - 1 > res.length())
            res = s.substr(L + 1, R - L - 1);
    }
};

Guess you like

Origin www.cnblogs.com/zzw1024/p/12334059.html
Recommended