-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
LonRep.cpp
70 lines (61 loc) · 1.83 KB
/
LonRep.cpp
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
// C++ program to find the longest repeated
// subsequence
#include <bits/stdc++.h>
using namespace std;
// This function mainly returns LCS(str, str)
// with a condition that same characters at
// same index are not considered.
string longestRepeatedSubSeq(string str)
{
// THIS PART OF CODE IS SAME AS BELOW POST.
// IT FILLS dp[][]
// https://www.geeksforgeeks.org/longest-repeating-subsequence/
// OR the code mentioned above.
int n = str.length();
int dp[n+1][n+1];
for (int i=0; i<=n; i++)
for (int j=0; j<=n; j++)
dp[i][j] = 0;
for (int i=1; i<=n; i++)
for (int j=1; j<=n; j++)
if (str[i-1] == str[j-1] && i != j)
dp[i][j] = 1 + dp[i-1][j-1];
else
dp[i][j] = max(dp[i][j-1], dp[i-1][j]);
// THIS PART OF CODE FINDS THE RESULT STRING USING DP[][]
// Initialize result
string res = "";
// Traverse dp[][] from bottom right
int i = n, j = n;
while (i > 0 && j > 0)
{
// If this cell is same as diagonally
// adjacent cell just above it, then
// same characters are present at
// str[i-1] and str[j-1]. Append any
// of them to result.
if (dp[i][j] == dp[i-1][j-1] + 1)
{
res = res + str[i-1];
i--;
j--;
}
// Otherwise we move to the side
// that that gave us maximum result
else if (dp[i][j] == dp[i-1][j])
i--;
else
j--;
}
// Since we traverse dp[][] from bottom,
// we get result in reverse order.
reverse(res.begin(), res.end());
return res;
}
// Driver Program
int main()
{
string str = "AABEBCDD";
cout << longestRepeatedSubSeq(str);
return 0;
}