码迷,mamicode.com
首页 > 其他好文 > 详细

5. Longest Palindromic Substring

时间:2020-03-05 11:52:43      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:color   The   span   tput   may   字符   self   while   div   

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"
class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        
        res = ""
        
        # 遍历字符串,以单字符或双字符为中心,向两边扩展,保留最大长度
        for i in xrange(len(s)):
            odd = self.helper(s, i, i)
            even = self.helper(s, i, i+1)
            
            res = max(res, odd, even, key=len)
        
        return res
        
    def helper(self, s, l, r):
        
        while l >= 0 and r < len(s) and s[l] == s[r]:
            l -= 1
            r += 1
        
        return s[l+1:r]

 

5. Longest Palindromic Substring

标签:color   The   span   tput   may   字符   self   while   div   

原文地址:https://www.cnblogs.com/boluo007/p/12419271.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!