I am doing the Leetcode question of Find the Longeest Palindromic Substring.
For example if the input babad then the output can be bab or aba.
OR
if the input is cbbd then the output is bb.
I'm pretty sure I have it figured out, this is my code...
def longestPalindrome(self, s):
n = len(s)
# Empty matrix.
table = [[False for i in range(n)] for j in range(n)]
# Identity matrix.
for i in range(n):
table[i][i] = True
max_len = 0
start = 0
finish = 0
for sil in range(2, n+1):
for i in range(n-sil + 1):
j = sil + i - 1
if sil == 2:
if s[i] == s[j]:
table[i][j] = True
max_len = j-i
start = i
finish = j
else:
if s[i] == s[j] and table[i+1][j-1]:
table[i][j] = True
if (j - i) > finish-start:
max_len = j - i
start = i
finish = j
return s[start:finish+1]
It works on most cases except for when the string is extremely long. I am submitting my code and it is failing on the following case...
"esbtzjaaijqkgmtaajpsdfiqtvxsgfvijpxrvxgfumsuprzlyvhclgkhccmcnquukivlpnjlfteljvykbddtrpmxzcrdqinsnlsteonhcegtkoszzonkwjevlasgjlcquzuhdmmkhfniozhuphcfkeobturbuoefhmtgcvhlsezvkpgfebbdbhiuwdcftenihseorykdguoqotqyscwymtjejpdzqepjkadtftzwebxwyuqwyeegwxhroaaymusddwnjkvsvrwwsmolmidoybsotaqufhepinkkxicvzrgbgsarmizugbvtzfxghkhthzpuetufqvigmyhmlsgfaaqmmlblxbqxpluhaawqkdluwfirfngbhdkjjyfsxglsnakskcbsyafqpwmwmoxjwlhjduayqyzmpkmrjhbqyhongfdxmuwaqgjkcpatgbrqdllbzodnrifvhcfvgbixbwywanivsdjnbrgskyifgvksadvgzzzuogzcukskjxbohofdimkmyqypyuexypwnjlrfpbtkqyngvxjcwvngmilgwbpcsseoywetatfjijsbcekaixvqreelnlmdonknmxerjjhvmqiztsgjkijjtcyetuygqgsikxctvpxrqtuhxreidhwcklkkjayvqdzqqapgdqaapefzjfngdvjsiiivnkfimqkkucltgavwlakcfyhnpgmqxgfyjziliyqhugphhjtlllgtlcsibfdktzhcfuallqlonbsgyyvvyarvaxmchtyrtkgekkmhejwvsuumhcfcyncgeqtltfmhtlsfswaqpmwpjwgvksvazhwyrzwhyjjdbphhjcmurdcgtbvpkhbkpirhysrpcrntetacyfvgjivhaxgpqhbjahruuejdmaghoaquhiafjqaionbrjbjksxaezosxqmncejjptcksnoq"
The error message is Time Limit Exceeded.
Why is this? I am doing a Dynamic Programming solution which should be an accepted answer.