python版 最长回文字符串
程序员文章站
2022-06-22 16:36:27
# 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。 # # 示例 1: # # 输入: "babad"# 输出: "bab"# 注意: "aba" 也是一个有效答案。# # # 示例 2: # # 输入: "cbbd"# 输出: "bb"# # Related Topics 字符串 动态规划 # ???? 2959 ???? 0# leetcode submit region begin(Prohibit modi...
# 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
#
# 示例 1:
#
# 输入: "babad"
# 输出: "bab"
# 注意: "aba" 也是一个有效答案。
#
#
# 示例 2:
#
# 输入: "cbbd"
# 输出: "bb"
#
# Related Topics 字符串 动态规划
# ???? 2959 ???? 0
# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
def center(self, left, right, s):
step = []
if left == right:
k = 1
while left - k >= 0 and left + k < len(s):
if s[left - k] == s[left + k]:
step = s[left - k: right + k + 1]
k += 1
else:
break
if left + 1 == right:
k = 0
while left - k >= 0 and right + k < len(s):
if s[left - k] == s[right + k]:
step = s[left - k: right + k + 1]
k += 1
else:
break
return step
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
l = []
for i in range(0, len(s) - 1):
step1 = self.center(i, i, s)
step2 = self.center(i, i + 1, s)
if len(l) < max(len(step1), len(step2)):
if len(step1) > len(step2):
l = step1
else:
l = step2
if l == []:
return s[0]
return l
# s = "bbbbb"
# o = Solution()
# print(o.longestPalindrome(s))
# leetcode submit region end(Prohibit modification and deletion)
本文地址:https://blog.csdn.net/weixin_41863544/article/details/110493234
上一篇: GitLab任意文件读取漏洞(CVE-2020-10977)复现
下一篇: 力扣题解