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.
You are not breaking out of your inner loop early, so you are still doing O(n²) work in all cases.
Consider that a palindrome must have either 'xx' or 'x?x' at its center. Where x is any character that appears twice, and ? is any character.
This probably doesn't improve worst case running time for some pathalogical cases, but at least in the example you provided it should save you a lot of computation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With