首页 > 编程语言 > 详细

leetcode Longest Palindromic Substring python

时间:2015-11-08 22:02:32      阅读:256      评论:0      收藏:0      [点我收藏+]
class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        lenStr = len(s)
        if lenStr <= 0:
            return 0
        maxLen = 0
        tmpLen = 0
        tmpRes = ‘‘
        for i in range(0,lenStr):
            
            #odd numbers
            j=0
            tmpLen=0
            while i-j >= 0 and i+j < lenStr and s[i-j] == s[i+j]:
                tmpLen = 2*j +1
                j+=1
            if tmpLen > maxLen:
                maxLen = tmpLen
          #i-j+1 plus one because first: j+=1 then judge s[i-j] == s[i+i]
                #so when the while cycle stop, the j is bigger one than the j that make while condition establish 
                tmpRes = s[i-j+1:i+j]
            #even numbers
            j=0
            tmpLen=0
            while i-j>=0 and i+j+1 < lenStr and s[i-j] == s[i+j+1]:
                tmpLen = 2*j + 2
                j+=1
            if tmpLen > maxLen:
                maxLen = tmpLen
                tmpRes = s[i-j+1:i+j+1]
        return tmpRes
 

 

leetcode Longest Palindromic Substring python

原文:http://www.cnblogs.com/allenhaozi/p/4948105.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!