data-sree / Python_codes

0 stars 0 forks source link

Longest_Palindromic_Substring.py #3

Closed Nirmal1901 closed 5 months ago

Nirmal1901 commented 5 months ago

About the code: The provided code is a Python function that takes a string as input and returns the longest palindrome in the string. The function uses a brute force approach, iterating over each character in the string and checking if it forms a palindrome. If it does, the function updates the start index and maximum length of the palindrome.

Status: Good

Issues: None

Improved code: The provided code can be improved by using a more efficient approach to find the longest palindrome in a string. One such approach is to use a dynamic programming algorithm, which involves creating a two-dimensional array where the rows represent the characters in the input string and the columns represent the possible starting indices of the palindromes. The value at each cell in the array represents the length of the longest palindrome that can be formed by combining the character at the current row with the character at the current column. This approach would reduce the time complexity of the function from O(n^2) to O(n), where n is the length of the input string.

Here's an example of how the improved code could look like:

def longest_palindrome(s):
    # Create a two-dimensional array to store the lengths of palindromes
    dp = [[0] * len(s) for _ in range(len(s))]

    # Initialize the first row and column with 1
    for i in range(len(s)):
        dp[i][i] = 1

    # Fill in the rest of the array
    for i in range(1, len(s)):
        for j in range(0, len(s) - i):
            if s[j] == s[j + i]:
                dp[j][j + i] = 2
            else:
                dp[j][j + i] = max(dp[j + 1][j + i], dp[j][j + i - 1])

    # Find the longest palindrome by traversing the array
    max_len = 0
    start = 0
    for i in range(len(s)):
        for j in range(i, len(s)):
            if dp[i][j] > max_len:
                max_len = dp[i][j]
                start = i

    # Return the longest palindrome
    return s[start:start + max_len]
data-sree commented 5 months ago

Thanks for the inputs. Appreciated