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

【5.最长回文子串】【python】
This commit is contained in:
BruceCat 2021-03-21 12:11:51 +08:00 committed by GitHub
commit 637f40d59e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 34 additions and 0 deletions

View File

@ -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/) ,也是类似的题目