Leetcode5:Longest Palindromic Substring@Python

时间:2021-11-29 13:59:41

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

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

Example:

Input: "cbbd"

Output: "bb"

动态规划法:以"ababae"为例:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAmsAAAD0CAIAAABLgfYMAAARXklEQVR4nO2dwZni3BJDOy4CIh6iIRmCqX/RMwMuevPcdXUf0jnL2WjOJ9syBpqvAgAAgP+dr93/AQAAgI+EBQUAADgDCwoAAHAGFhQAAOAMLCgAAMAZWFAAAIAzsKAAAABnYEEBAADOwIICAACcgQUFAAA4AwsKAABwBhYUAADgDCwoAADAGVhQAACAM7CgAAAAZ2BBAQAAzsCCAgAAnIEFBQAAOAMLCgAAcAYWFAAA4AwsKAAAwBlYUAAAgDOwoAAAAGdgQQEAAM7AggIAAJyBBQUAADjDhgX9AgAAWIxizgQZPVIi9v8Apn5gakmOLKbDKYKMHkmFdmDqR45pJcliOpwiyOiRVGgHpn7kmFaSLKbDKYKMHkmFdmDqR45pJcliOpwiyOiRVGgHpn7kmFaSLKbDKYKMHkmFdmDqR45pJcliOpwiyOiRVGiH0vR+/fq63B6yvCN0uoK9nRa1OsKCfjyYroAF1ZDTaVGrIyzox4PpClhQDTmdFrU6woJ+PJiugAXVkNNpUasjLOjHozV93C7PP2d1vQuTt1xt79ctsnS6gr2dFrWu46VTsSoL+vEITR+3y/P4fNwu4lt69dX26+knlqXTFezttKh1DY/b5au5CkeUBf14tpmqj9W9T/ykjwDpdAV7Oy1qXcL92tTe/mEpLOjHs/HRkPGzzbeLq/QiRKcr2NtpUesKuuXX4TnDeljQj0d8u7fveUnQ1ZZOV5C0oDG1ytUaLOjHs+1gNT4tdz/xo9MVBD3FDap18yesWdCPZ9ON7Z+nJ6anZf/UyfGWfjl0uoK9nRa1rqF/Tup+VS4qC/rxSE0P3wTQvmWvv9pe7y9vsth+lJFOZVDrIg5vh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s4/PSg9Q8UYyogx7S0sjmmf/gWNjVlQRciPy3Nfw7+G0w15JiWUDbH9JvnL2yzoGORLOg892v7Cfi3f1gKpgvAVJWvk80xrXreLjxuFxZ0MFK8oM+7IN/bvfdDVHvQYjoPpsKTVSSbY3qABZ2NVN8E/atOXaTO9Ic7WenNLabzYCp8aSaSzTE9wILORmqfDh2Ke/uHpeRcgzCdB1O/XckxPcCCzkZqnw694fhO0u4zE9N5MPXblRzTAyzobOTG91e05LyThOk8mPq9O5hjeoAFnY3c+Bk/LRtNjx+aXw6mC8BUlb/vs7i+pq+woLOR275nVnW/Kg9Xpen9+vqA2vm7g5hqyDEtoWyO6Qss6Gzkxr91on1Buu3Ly/JX3pguAlMN8tuFCNOfPoji9hDFf0E3gqkfmFqSI4vpcIogo0dSoR2Y+pFjWkmymA6nCDJ6JBXagakfOaaVJIvpcIogo0dSoR2Y+pFjWkmymA6nCDJ6JBXagakfOaaVJIvpcIogo0dSoR2Y+pFjWkmymA6nCDJ6JBXagakfOaaVJIvpcIogo0dSoR2Y+pFjWkmymA6nCDJ6JAAAwGIUcybIAAAA8IMFBQAAOAMLCgAAcAYWFAAA4AwsKAAAwBlYUAAAgDOwoAAAAGdgQQEAAM7AggIAAJyBBQUAADgDCwoAAHAGFhQAAOAMLCgAAMAZWFAAAIAzsKAAAABnYEEBAADOwIICAACcgQUFAAA4AwsKAABwBhYUAADgDCwoAADAGVhQAACAM7CgAAAAZ2BBAQAAzsCCAgAAnIEFBQAAOAMLCgAAcAYWFAAA4Az/AZpE1th2lqslAAAAAElFTkSuQmCC" alt="" width="548" height="207" />
 class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
sLength=len(s)
begin=0
length=0
table=[]
for i in range(sLength):
tem=[]
for j in range(sLength):
tem.append(0)
table.append(tem) for i in range(sLength):
table[i][i]=1 for i in range(sLength-1):
if s[i]==s[i+1]:
table[i][i+1]=1
begin=i
length=1 for tem in range(1,sLength):
for i in range(sLength-tem):
j=i+tem
if (s[i]==s[j] and table[i+1][j-1])==1:
table[i][j]=1
length=tem
begin=i return s[begin:begin+length+1]