imashutosh51

Longest Palindromic substring

Jul 25th, 2022 (edited)
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.08 KB | None | 0 0
  1. '''
  2. M-1: Brute Force
  3. We should traverse all the substring for(i->n)-> for (j=i+1->n) and check all the substring by reversing that if matching, store the max size substring. two loops-> n*n and one loop for checking so Time Complexity= N^3
  4.  
  5. M-2:
  6. We will still go to all the subtring but can we do two string comparison optimally? so suppose you are at i and j indices of string and you want to check substring from i->j is a palindrome or not?, so if ith and jth character matches then you will need to check is i-1th and j+1th character matches or not, if yes then we will do again in deep on shorter string until it doesn't cross the j and if it croseed, means all were mathching but if ith and jth  character doesn't match at any point, it means it is simply str[i->j] is not the palindrome.
  7.  
  8. so we will use DP where rows are the starting indices and columns are the ending indices so dp dimension=N*N where dp table will contain eg dp[i][j]=True/False where True means str[i->j] substring is palindrome or not
  9. we will check if s[i]==s[j] if yes->go deeper on s[i-1],s[j-1] else return False and keep updating the dp table before returning.
  10.  
  11. we will call the function for all the substring(2 for loops) and if function returns true, you can compare the ans lenght and store the palindrom substring.
  12.  
  13. Some points to remeber:
  14. 1.initially the answer will be having the first char because answer can be minimum as 1 char because single char will always be palindrome
  15. '''
  16. def fun(s,i,j,dp):
  17.     if i>=j:
  18.         return True
  19.     if dp[i][j]!=-1:
  20.         return dp[i][j]
  21.     if s[i]!=s[j]:
  22.         return False
  23.     dp[i][j]= fun(s,i+1,j-1,dp)
  24.     return dp[i][j]
  25. class Solution:
  26.     def longestPalindrome(self, s: str) -> str:
  27.         dp=[[-1]*len(s) for _ in range(len(s))]
  28.         ans=1
  29.         str=s[0]
  30.         for i in range(len(s)):
  31.             for j in range(i+1,len(s)):
  32.                 if fun(s,i,j,dp)==True:
  33.                     dp[i][j]=True
  34.                     if ans<j-i+1:
  35.                         str=s[i:j+1]
  36.                         ans=max(ans,j-i+1)
  37.         return str
  38.        
Advertisement
Add Comment
Please, Sign In to add comment