[leetcode] 5. Longest Palindromic Substring @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/86682433

原题

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”

解法

参考: Python easy to understand solution with comments (from middle to two ends).
遍历字符串, 寻找在i 点时能构成的最长回文, 回文有两种情况: 1) 奇数长度, 如’aba’. 2) 偶数长度, 如’abba’, 每次遍历时更新res.
Time: O(n)
Space: O(1)

代码

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        def getPalindrome(s, l, r):
            while l >= 0 and r < len(s) and s[l] == s[r]:
                l -= 1
                r += 1
            return s[l+1:r]
        
        res = ''
        for i in range(len(s)):
            # odd case, like 'aba'
            sub = getPalindrome(s, i, i)
            if len(sub) > len(res):
                res = sub
            # even case, like 'abba'
            sub = getPalindrome(s, i, i+1)
            if len(sub) > len(res):
                res = sub
        return res

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/86682433