【发布时间】:2019-08-29 20:57:52
【问题描述】:
我为 leetcode "5. Longest Palindromic Substring" 提出了一个解决方案,其中包含部分重复代码。解决重复代码的好方法之一是创建一个函数。如何在此处将支票写入函数?我很困惑我应该返回什么来使两个变量 - 最长和 ans - 被更新。谢谢!
重复代码部分:
if len(s[l:r+1]) > longest:
longest = len(s[l:r+1])
ans = s[l:r+1]
完整代码:
class Solution:
def longestPalindrome(self, s: str) -> str:
if len(s) == 0:
return ''
if len(s) == 1:
return s
longest = 0
ans = ''
for pos in range(len(s)-1):
l, r = pos, pos
if pos > 0 and pos < len(s) - 1 and s[pos-1] == s[pos+1]:
l, r = pos-1, pos+1
while l > 0 and r < len(s) - 1 and s[l-1] == s[r+1]:
l -= 1
r += 1
# duplicate code 1
if len(s[l:r+1]) > longest:
longest = len(s[l:r+1])
ans = s[l:r+1]
if s[pos] == s[pos+1]:
l, r = pos, pos+1
while l > 0 and r < len(s) - 1 and s[l-1] == s[r+1]:
l -= 1
r += 1
# duplicate code 2
if len(s[l:r+1]) > longest:
longest = len(s[l:r+1])
ans = s[l:r+1]
if ans == '' and len(s) > 0:
return s[0]
return ans
【问题讨论】:
标签: python-3.x function