5. Longest Palindromic Substring

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

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

Code:

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        # short string
        size = len(s)
        if size == 1:
            return s
        if size == 2:
            if s[0] == s[1]:
                return s
            return s[0]
        # long string
        maxp = 1
        # empty result string
        ans = s[0]
        i = 0
        # travlsal s
        while i < size:
            j = i + 1
            # judge if two nearly char  equal
            while j < size:  #size=5
                if s[i] == s[j]:#s[0]=a s[1]=a ->j=2 ->s[0]=a s[2]=b ->break
                    j += 1
                else:
                    break
            k = 0
            # speard s from s[i]
            while i - k - 1 >= 0 and j + k<= size - 1:#(i=1)-k-1=0=0 (j=2)+0=2<(size=5)
                # not eaual and break
                if s[i- k - 1] != s[j + k]:#s[i-k-1]=a s[j+k]=b ->break
                    break
                # eaual and continue
                k += 1  #k=1
            if j - i + 2*k > maxp:  #j-i+2*k=2-0+2*1=0<mxp=1
                maxp = j- i + 2*k   
                ans = s[i - k:j + k]
            if j + k == size - 1: #2+1=3!=5 
                break
            i = j       #i=2
        return ans