1
+
2
+ // C++ program to find the longest repeated
3
+ // subsequence
4
+ #include < bits/stdc++.h>
5
+ using namespace std ;
6
+
7
+ // This function mainly returns LCS(str, str)
8
+ // with a condition that same characters at
9
+ // same index are not considered.
10
+ string longestRepeatedSubSeq (string str)
11
+ {
12
+ // THIS PART OF CODE IS SAME AS BELOW POST.
13
+ // IT FILLS dp[][]
14
+ // https://www.geeksforgeeks.org/longest-repeating-subsequence/
15
+ // OR the code mentioned above.
16
+ int n = str.length ();
17
+ int dp[n+1 ][n+1 ];
18
+ for (int i=0 ; i<=n; i++)
19
+ for (int j=0 ; j<=n; j++)
20
+ dp[i][j] = 0 ;
21
+ for (int i=1 ; i<=n; i++)
22
+ for (int j=1 ; j<=n; j++)
23
+ if (str[i-1 ] == str[j-1 ] && i != j)
24
+ dp[i][j] = 1 + dp[i-1 ][j-1 ];
25
+ else
26
+ dp[i][j] = max (dp[i][j-1 ], dp[i-1 ][j]);
27
+
28
+
29
+ // THIS PART OF CODE FINDS THE RESULT STRING USING DP[][]
30
+ // Initialize result
31
+ string res = " " ;
32
+
33
+ // Traverse dp[][] from bottom right
34
+ int i = n, j = n;
35
+ while (i > 0 && j > 0 )
36
+ {
37
+ // If this cell is same as diagonally
38
+ // adjacent cell just above it, then
39
+ // same characters are present at
40
+ // str[i-1] and str[j-1]. Append any
41
+ // of them to result.
42
+ if (dp[i][j] == dp[i-1 ][j-1 ] + 1 )
43
+ {
44
+ res = res + str[i-1 ];
45
+ i--;
46
+ j--;
47
+ }
48
+
49
+ // Otherwise we move to the side
50
+ // that that gave us maximum result
51
+ else if (dp[i][j] == dp[i-1 ][j])
52
+ i--;
53
+ else
54
+ j--;
55
+ }
56
+
57
+ // Since we traverse dp[][] from bottom,
58
+ // we get result in reverse order.
59
+ reverse (res.begin (), res.end ());
60
+
61
+ return res;
62
+ }
63
+
64
+ // Driver Program
65
+ int main ()
66
+ {
67
+ string str = " AABEBCDD" ;
68
+ cout << longestRepeatedSubSeq (str);
69
+ return 0 ;
70
+ }
0 commit comments