LeetCode #5 -- Longest Palindromic Substring

A propose solution for finding largest Palindromic Substring
mail@pastecode.io avatar
a year ago
1.3 kB
# Avi C. Solution for LeetCode #5 -- Longest Palindromic Substring
# The algorthinm:
# By given string - loop through each letter and find closet similiar letter
# extract this as substring .
# create a revese list from the substring and compare the element are eq

s = "abzsaba"

def is_pali (string:str) -> bool:
    # copy list in revese order
    # for pali this mean and exact same list
    string_reversed = string[::-1]  
    # using zip command we can check if both are eq
    for i,j in zip(string,string_reversed):
        if i != j:
            return False
    return True

def palindromic_scan(s:str) -> str:
    all_pali ={}
    for t, letter in enumerate(s):
        # search for the next similiar letter
        for idx, l in enumerate(s[t+1:]):
            if l == letter:
                # extract the substring strarting first letter till next same letter (suspicious be pali)
                sub_pal = s[t:t+idx+2]
                if is_pali(sub_pal):
                    # save all pali string while key is the length and val is the string
                    all_pali[len(sub_pal)] = sub_pal
    # return the string by max length
    return all_pali[max(all_pali)]