Advertisement
Iam_Sandeep

Print LCS string using memoization

Jul 29th, 2022 (edited)
714
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.56 KB | None | 0 0
  1. m,n=len(s1),len(s2)
  2. dp={}
  3. def lcs(i,j):
  4.     if (i,j)in dp:return dp[i,j]
  5.     if i==m or j==n:
  6.         dp[i,j]=0
  7.     else:
  8.         if s1[i]==s2[j]:
  9.             dp[i,j]=1+lcs(i+1,j+1)
  10.         else:
  11.             dp[i,j]=max(lcs(i+1,j),lcs(i,j+1))
  12.    
  13.     return dp[i,j]
  14. for i in range(m+1):
  15.     for j in range(n+1):
  16.         if (i,j) not in dp:
  17.             lcs(i,j)
  18.  
  19. i,j,item=0,0,[]
  20. while i<m and j<n:
  21.     if s1[i]==s2[j]:
  22.         item.append(s1[i])
  23.         i,j=i+1,j+1
  24.     elif dp[i+1,j]>dp[i,j+1]:
  25.         i=i+1
  26.     else:
  27.         j=j+1
  28. print(item)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement