首页 > 其他 > 详细

LeetCode——005 Longest Palindromic Substring

时间:2020-02-20 00:59:59      阅读:74      评论:0      收藏:0      [点我收藏+]

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

LeetCode——005 Longest Palindromic Substring

原文:https://www.cnblogs.com/zzw1024/p/12334059.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!