Advertisement
Iam_Sandeep

Longest Repeating Subsequence

Aug 1st, 2022
878
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | None | 0 0
  1. '''
  2. Given string str, find the length of the longest repeating subsequence such that it can be found twice in the given string.
  3.  
  4. The two identified subsequences A and B can use the same ith character from string str if and only if that ith character has different indices in A and B. For example, A = "xax" and B = "xax" then the index of first "x" must be different in the original string for A and B.
  5. '''
  6. class Solution:
  7.     def LongestRepeatingSubsequence(self, s):
  8.         dp={}
  9.         n=len(s)
  10.         def lrs(i,j):
  11.             #print((i,j))
  12.             if (i,j) in dp:return dp[(i,j)]
  13.             if i==n or j==n:return 0
  14.             ans=None
  15.             if s[i]==s[j] and i!=j:
  16.                 ans=1+lrs(i+1,j+1)
  17.             else:
  18.                 ans=max(lrs(i,j+1),lrs(i+1,j))
  19.             dp[(i,j)]=ans
  20.             return ans
  21.         return lrs(0,0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement