您的位置:首页 > 编程语言 > Python开发

python写算法题:leetcode: 5. Longest Palindromic Substring

2017-06-02 08:52 671 查看
https://leetcode.com/problems/longest-palindromic-substring/#/description

class Solution(object):
def palindrome(self, s, centpos):
ind0=0
while True:
if centpos-ind0<0 or centpos+ind0>=len(s): break
if s[centpos+ind0]!=s[centpos-ind0]:break
ind0+=1

ind1=0
while True:
if centpos-ind1<0 or centpos+ind1+1>=len(s): break
if s[centpos+ind1+1]!=s[centpos-ind1]:break
ind1+=1
#print "got:",s, centpos, ind0, ind1
if ind0*2-1 > ind1*2:
return s[centpos-ind0+1:centpos+ind0]
else:
return s[centpos-ind1+1:centpos+ind1+1]

def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if len(s)<2: return s
shalflen = len(s)/2
maxlen=0
maxret=""
for ind in xrange(shalflen+1):
if maxlen/2>shalflen-ind: break
ret=self.palindrome(s,shalflen-ind)
ret1=""
if ind>0:
ret1=self.palindrome(s,shalflen+ind)
if len(ret)>maxlen:
maxlen = len(ret)
maxret=ret
if len(ret1)>maxlen:
maxlen = len(ret1)
maxret=ret1
return maxret


思路:从字符串中间的位置开始找起,避免不必要的检查
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: