File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments