Skip to content

Commit 148cff1

Browse files
committed
Longest repeating subsequence using c++
1 parent da0f341 commit 148cff1

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
2+
/*
3+
Given a string, find the length of the longest repeating subsequence such that the two subsequences don't have same string character at the same position, i.e., any i'th character in the two subsequences shouldn't have the same index in the original string.
4+
5+
6+
7+
Example 1:
8+
9+
Input: str = "axxxy"
10+
Output: 2
11+
Explanation: The longest repeating subsequenece
12+
is "xx".
13+
*/
14+
15+
#include<bits/stdc++.h>
16+
using namespace std;
17+
18+
// } Driver Code Ends
19+
class Solution {
20+
public:
21+
int LongestRepeatingSubsequence(string str){
22+
// Code here
23+
int n = str.length();
24+
25+
// Create and initialize DP table
26+
int dp[n+1][n+1];
27+
for (int i=0; i<=n; i++)
28+
for (int j=0; j<=n; j++)
29+
dp[i][j] = 0;
30+
31+
// Fill dp table (similar to LCS loops)
32+
for (int i=1; i<=n; i++)
33+
{
34+
for (int j=1; j<=n; j++)
35+
{
36+
// If characters match and indexes are
37+
// not same
38+
if (str[i-1] == str[j-1] && i != j)
39+
dp[i][j] = 1 + dp[i-1][j-1];
40+
41+
// If characters do not match
42+
else
43+
dp[i][j] = max(dp[i][j-1], dp[i-1][j]);
44+
}
45+
}
46+
return dp[n][n];
47+
}
48+
49+
};
50+
51+
52+
int main(){
53+
int tc;
54+
cin >> tc;
55+
while(tc--){
56+
string str;
57+
cin >> str;
58+
Solution obj;
59+
int ans = obj.LongestRepeatingSubsequence(str);
60+
cout << ans << "\n";
61+
}
62+
return 0;
63+
}

0 commit comments

Comments
 (0)