-
Notifications
You must be signed in to change notification settings - Fork 0
/
30. Longest repeating subsequence
71 lines (56 loc) · 1.56 KB
/
30. Longest repeating subsequence
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
30 .Longest repeating subsequence
Video Link : https://youtu.be/hbTaCmQGqLg
GFG Practice Link: https://practice.geeksforgeeks.org/problems/longest-repeating-subsequence2004/1
Approach : i). make another copy of the string
ii). now find the LCS with the condition that characters should have not same index i.e if str1[i-1]==str2[j-1] then i != j .
iii). Now return the length of LCS .
------->>>>>>>>>>>------------>>>>>>>>>>>>________CODE________<<<<<<<<<<<<------------<<<<<<<<<<<<<<<<<<<<<<<<<<<
//{ Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
int LongestRepeatingSubsequence(string str){
// Code here
int n= str.size();
string a=str;
vector<vector<int>> dp (n+1, vector<int> ( n+1));
for(int i=0;i<n+1;i++)
{
dp[i][0]=0;
}
for(int i=0;i<n+1;i++)
{
dp[0][i]=0;
}
for(int i=1;i<n+1;i++)
{
for(int j=1;j<n+1;j++)
{
if(str[i-1]==a[j-1] && i!=j)
{
dp[i][j]= 1+ dp[i-1][j-1];
}
else{
dp[i][j]= max(dp[i-1][j], dp[i][j-1]);
}
}
}
return dp[n][n];
}
};
//{ Driver Code Starts.
int main(){
int tc;
cin >> tc;
while(tc--){
string str;
cin >> str;
Solution obj;
int ans = obj.LongestRepeatingSubsequence(str);
cout << ans << "\n";
}
return 0;
}
// } Driver Code Ends