imashutosh51

Longest Common Substring

Mar 6th, 2026 (edited)
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.63 KB | None | 0 0
  1. '''
  2. Variatin of maximum lenght subsequence:
  3. Here you have to return the maximum lenght of the substring possible between s1 and s2.
  4. we check the nth and mth character and if matches, we add the 1 in answer and then check for n-1th and m-1th char.
  5. if Not matches, then obviously the s1 of length n and s2 of length m have 0 matching from the backwards(as we are checking from backside). so we will populate 0 in dp table.
  6.  
  7. so as we know,what function returns so we will have to check all the possibilities of strings as function only tells the max len substring from backside mathcing, so in main function we will run on the whole string where fun(s1,s2,i,j) returns the maximum length of the substrings in strings s1 ending at ith char and s2 ending at jth char possible from the backside so we are checking all the substring which also means all the n & m possible.
  8.  
  9.  
  10. Base condition:
  11. 1)if n<0 or m<0 means atleast one string got over, so there can't be any substring,so return 0.
  12.  
  13. Time complexity: O(n*m) as there are n*m states.
  14. '''
  15. def fun(s1,s2,n,m,dp): #this tell the max length of substring s1[:n] & s2[:m] and checked from the backside so we will to check for all the sublengths.
  16.     if n<0 or m<0:
  17.         return 0
  18.     if dp[n][m]!=-1:
  19.         return dp[n][m]
  20.     if s1[n]==s2[m]:
  21.         dp[n][m]=1+fun(s1,s2,n-1,m-1,dp)
  22.     else:
  23.         dp[n][m]=0
  24.     return dp[n][m]
  25.  
  26.  
  27.  
  28. class Solution:
  29.     def longCommSubstr(self, s1, s2):
  30.         dp=[[-1]*len(s2) for _ in range(len(s1))]
  31.         ans=0
  32.         for i in range(len(s1)):
  33.             for j in range(len(s2)):
  34.                 ans=max(ans,fun(s1,s2,i,j,dp))
  35.         return ans
Advertisement
Add Comment
Please, Sign In to add comment