码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode Longest Palindromic Substring python

时间:2015-11-08 22:04:23      阅读:299      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!