# 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。## 示例 1:## 输入: "babad"# 输出: "bab"# 注意: "aba" 也是一个有效答案。### 示例 2:## 输入: "cbbd"# 输出: "bb"## Related Topics 字符串 动态规划# 👍 2558 👎 0# leetcode submit region begin(Prohibit modification and deletion)class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ max_l = 0 res = "" for i in range(0, len(s)): # s[i] 为中心 left, right = i, i while left >= 0 and right < len(s) and s[left] == s[right]: if max_l < right - left + 1: max_l = right - left + 1 res = s[left:right + 1] left -= 1 right += 1 # s[i] s[i+1] 为中心 left, right = i, i + 1 while left >= 0 and right < len(s) and s[left] == s[right]: if max_l < right - left + 1: max_l = right - left + 1 res = s[left:right + 1] left -= 1 right += 1 return res# leetcode submit region end(Prohibit modification and deletion)s = Solution()print(s.longestPalindrome("babad"))print(s.longestPalindrome("cbbd"))
class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ start, end = 0, 0 for index, item in enumerate(s): left1, right1 = self.expandAroundCenter(s, index, index) left2, right2 = self.expandAroundCenter(s, index, index + 1) if right1 - left1 > end - start: start, end = left1, right1 if right2 - left2 > end - start: start, end = left2, right2 return s[start: end + 1] def expandAroundCenter(self, s, left, right): while left > 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 return left + 1, right - 1