-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path5.最长回文子串.py
More file actions
37 lines (29 loc) · 892 Bytes
/
5.最长回文子串.py
File metadata and controls
37 lines (29 loc) · 892 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#
# @lc app=leetcode.cn id=5 lang=python3
#
# [5] 最长回文子�?
#
# @lc code=start
class Solution:
def longestPalindrome(self, s: str) -> str:
res = ""
# i表示中心, 枚举每个回文字符中心
# 由左右两个指针l,r分别左右移动
for i in range(len(s)):
# 回文字符为奇数
l, r = i-1, i+1
while (l >= 0 and r < len(s) and s[l] == s[r]):
l = l-1
r = r+1
# 更新res
if (r-l-1 > len(res)):
res = s[l+1:r]
# 回文字符为偶数
l, r = i, i+1
while (l >= 0 and r < len(s) and s[l] == s[r]):
l = l-1
r = r+1
if (r-l-1 > len(res)):
res = s[l+1:r]
return res
# @lc code=end