3

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.

buydadip
  • 8,890
  • 22
  • 79
  • 154

1 Answers1

1

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.

Imran
  • 12,950
  • 8
  • 64
  • 79