Skip to content

Commit 637f40d

Browse files
authored
【5.最长回文子串】【python】
【5.最长回文子串】【python】
2 parents 6c7cfa4 + d83128b commit 637f40d

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

高频面试系列/最长回文子串.md

+34
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,40 @@ class Solution {
170170
}
171171
```
172172

173+
174+
[enrilwang](https://github.com/enrilwang) 提供 Python 代码:
175+
176+
```python
177+
# 中心扩展算法
178+
class Solution:
179+
def longestPalindrome(self, s: str) -> str:
180+
#用n来装字符串长度,res来装答案
181+
n = len(s)
182+
res = str()
183+
#字符串长度小于2,就返回本身
184+
if n < 2: return s
185+
for i in range(n-1):
186+
#oddstr是以i为中心的最长回文子串
187+
oddstr = self.centerExtend(s,i,i)
188+
#evenstr是以i和i+1为中心的最长回文子串
189+
evenstr = self.centerExtend(s,i,i+1)
190+
temp = oddstr if len(oddstr)>len(evenstr) else evenstr
191+
if len(temp)>len(res):res=temp
192+
193+
return res
194+
195+
def centerExtend(self,s:str,left,right)->str:
196+
197+
while left >= 0 and right < len(s) and s[left] == s[right]:
198+
left -= 1
199+
right += 1
200+
#这里要注意,跳出while循环时,恰好s[left] != s[right]
201+
return s[left+1:right]
202+
203+
204+
```
205+
206+
173207
做完这题,大家可以去看看 [647. 回文子串](https://leetcode-cn.com/problems/palindromic-substrings/) ,也是类似的题目
174208

175209

0 commit comments

Comments
 (0)