5. 最长回文子串_Longest Palindromic Substring

Longest Palindromic Substring

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

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

题目来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/longest-palindromic-substring

Example 1:

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

Example 2:

Input: "cbbd"
Output: "bb"

python3:

class Solution:
    def longestPalindrome(self, s: str) -> str:
        s_len = len(s)
        if s_len == 0:
            return ''
        longest_str = s[0]
        longest_len = 1
        for i in range(s_len):
            j = 1
            temp_len = 1
            while i - j >= 0 and i + j < s_len and s[i - j] == s[i + j]:
                temp_len = temp_len + 2
                j = j + 1
            if temp_len > longest_len:
                longest_len = temp_len
                longest_str = s[i - j + 1 : i + j]
            
            j = 0
            temp_len = 0
            while i - j >= 0 and i + j + 1 < s_len and s[i - j] == s[i + j + 1]:
                temp_len = temp_len + 2
                j = j + 1
            if temp_len > longest_len:
                longest_len = temp_len
                longest_str = s[i - j + 1 : i + j + 1]
        return longest_str
上一篇:最长回文子串


下一篇:5. 最长回文子串 Longest Palindromic Substring