未验证 提交 637f40d5 编写于 作者: B BruceCat 提交者: GitHub

【5.最长回文子串】【python】

【5.最长回文子串】【python】
......@@ -170,6 +170,40 @@ class Solution {
}
```
[enrilwang](https://github.com/enrilwang) 提供 Python 代码:
```python
# 中心扩展算法
class Solution:
def longestPalindrome(self, s: str) -> str:
#用n来装字符串长度,res来装答案
n = len(s)
res = str()
#字符串长度小于2,就返回本身
if n < 2: return s
for i in range(n-1):
#oddstr是以i为中心的最长回文子串
oddstr = self.centerExtend(s,i,i)
#evenstr是以i和i+1为中心的最长回文子串
evenstr = self.centerExtend(s,i,i+1)
temp = oddstr if len(oddstr)>len(evenstr) else evenstr
if len(temp)>len(res):res=temp
return res
def centerExtend(self,s:str,left,right)->str:
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
#这里要注意,跳出while循环时,恰好s[left] != s[right]
return s[left+1:right]
```
做完这题,大家可以去看看 [647. 回文子串](https://leetcode-cn.com/problems/palindromic-substrings/) ,也是类似的题目
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册