找出字符串的最长回文 python实现

来源:互联网 发布:剑灵天族捏脸数据图 编辑:程序博客网 时间:2024/06/05 04:51

在leetcode的solution中发现的一个非常容易理解的寻找最长回文的方法,题目如下:

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

class Solution(object):    def longestPalindrome(self, s):        res = ""        for i in xrange(len(s)):                        tmp = self.helper(s,i,i)            #odd case like aba            if(len(tmp)>len(res)):                res = tmp                            tmp = self.helper(s,i,i+1)            #even case like abba            if(len(tmp)>len(res)):                res = tmp        return res                # get the longest palindrome, l, r are the middle indexes       # from inner to outer                def helper(self,s,l,r):        while l>=0 and r<len(s) and s[l]==s[r]:            l -=1            r +=1        return s[l+1:r]

几点需要注意:

1. 在循环中 xrange 比 range 效率更高,推荐使用;

2. string[start:end]切片中,包涵 string start->end-1 下标的元素。

0 0