题解 | #密码截取#
密码截取
https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1
# 辅助函数,围绕中心扩展并检查回文
def expand(s, left, right):
# 当左右指针在边界内且字符相同时
while left >= 0 and right < len(s) and s[left] == s[right]:
# 向外移动指针
left -= 1
right += 1
# 返回回文的长度和子串
return right - left - 1, s[left + 1 : right]
# 主函数,查找最长回文子串
def longestPalindrome(s):
# 初始化最大长度和最大子串变量
max_len = 0
max_s = ""
# 遍历字符串中的每个字符
for i in range(len(s)):
# 围绕字符本身作为中心扩展
len1, s1 = expand(s, i, i)
# 围绕字符及其下一个作为中心扩展
len2, s2 = expand(s, i, i + 1)
# 选择两者中的更长回文子串
if len1 > len2:
curr_len = len1
curr_s = s1
else:
curr_len = len2
curr_s = s2
# 如果当前回文子串更长,则更新max_len和max_s变量
if curr_len > max_len:
max_len = curr_len
max_s = curr_s
# 返回最长回文子串
return max_s
# 测试你的代码
s = input()
print(len(longestPalindrome(s)))
自己的动规代码a了20/23,看看新bing写的
