题目
力扣题目:https://leetcode.cn/problems/longest-palindromic-substring/description/
给你一个字符串 s
,找到 s
中最长的回文子串。
如果字符串的反序与原始字符串相同,则该字符串称为回文字符串。
示例 1:
输入:s = "babad"n输出:"bab"n解释:"aba" 同样是符合题意的答案。n
示例 2:
输入:s = "cbbd"n输出:"bb"n
提示:
1 <= s.length <= 1000
s
仅由数字和英文字母组成
题解
要考虑两种情况:奇数长度的回文串和偶数长度的回文串。
首先,将最长回文子串 res
设为空字符串。
然后,遍历整个字符串,使用指针 i
。在每个位置向前寻找回文子串,但我们只需要找到长度大于 res
的回文子串,所以我们定位回文子串的开始位置为 start = max(0, i - len(res) - 1)
,结束位置为i
。
最后,根据选定的回文子串的索引范围对字符串进行切片,并判断是否为回文子串。这里需要注意,我们要考虑奇数长度和偶数长度的情况,如果找到更长的回文子串,就将其赋值给 res
。随着指针的遍历,res
的长度会逐渐增大,最终遍历结束后,res
就是最长的回文子串。
def longestPalindrome(s):n res = ''n for i in range(len(s)):n start = max(i - len(res) - 1, 0)n temp = s[start:i + 1]n if temp == temp[::-1]:n res = tempn elif temp[1:] == temp[1:][::-1]:n res = temp[1:]n return resnnnif __name__ == '__main__':n print(longestPalindrome('abcdeedcssw'))
Comments NOTHING