Skip to content

Commit

Permalink
【5.最长回文子串】【python】
Browse files Browse the repository at this point in the history
【5.最长回文子串】【python】
  • Loading branch information
brucecat authored Mar 21, 2021
2 parents 6c7cfa4 + d83128b commit 637f40d
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions 高频面试系列/最长回文子串.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/) ,也是类似的题目


Expand Down

0 comments on commit 637f40d

Please sign in to comment.