imashutosh51

Longest Repeating Subsequence

Mar 13th, 2026
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. '''
  2. LCS variation: We have to find the repeating subsequence, means if a is the subsequence of s then b should also exist in the s in the same order where each character's index of a should be different from b's, means one character can go in one subsequence only.
  3. Approach: find LCS with the same string, but if index of nth and mth character matches, don't consider it and rest is pure LCS.
  4. '''
  5. def fun(s1,s2,n,m,dp):
  6.     if n<0 or m<0:
  7.         return 0
  8.     if dp[n][m]!=-1:
  9.         return dp[n][m]
  10.     if s1[n]==s2[m] and n!=m:
  11.         dp[n][m]=1+fun(s1,s2,n-1,m-1,dp)
  12.     else:
  13.         dp[n][m]=max(fun(s1,s2,n-1,m,dp), fun(s1,s2,n,m-1,dp))
  14.     return dp[n][m]
  15.  
  16.  
  17. class Solution:
  18.     def LongestRepeatingSubsequence(self, s):
  19.         dp=[[-1]*len(s) for _ in range(len(s))]
  20.         return fun(s,s,len(s)-1,len(s)-1,dp)
Advertisement
Add Comment
Please, Sign In to add comment