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: **

使用中将对称思路
及从头开始遍历,对于每个字母进行左右向外扩散,判断是不是回文子串
注意,向外扩散有两种方式,第一种,就是以该字母为中心向外扩散,第二种就是该字母和其右端的字母开始进行向外扩散

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);
    }
};

猜你喜欢

转载自www.cnblogs.com/zzw1024/p/12334059.html