-
Notifications
You must be signed in to change notification settings - Fork 212
/
LongestRepeatingSubsequence.cpp
79 lines (64 loc) · 1.87 KB
/
LongestRepeatingSubsequence.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
71
72
73
74
75
76
77
78
79
/*Given a string str, find the length of the longest repeating subsequence such that it can be found twice in the given string.
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.
Input:
str = "axxxy"
Output: 2
Explanation:
The given array with indexes looks like
a x x x y
0 1 2 3 4
The longest subsequence is "xx".
It appears twice as explained below.
subsequence A
x x
0 1 <-- index of subsequence A
------
1 2 <-- index of str
subsequence B
x x
0 1 <-- index of subsequence B
------
2 3 <-- index of str
We are able to use character 'x'
(at index 2 in str) in both subsequences
as it appears on index 1 in subsequence A
and index 0 in subsequence B.
*/
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
int LongestRepeatingSubsequence(string str){
int n = str.length();
// Create and initialize DP table
int dp[n+1][n+1];
for (int i=0; i<=n; i++)
for (int j=0; j<=n; j++)
dp[i][j] = 0;
// Fill dp table (similar to LCS loops)
for (int i=1; i<=n; i++)
{
for (int j=1; j<=n; j++)
{
// If characters match and indexes are
// not same
if (str[i-1] == str[j-1] && i != j)
dp[i][j] = 1 + dp[i-1][j-1];
// If characters do not match
else
dp[i][j] = max(dp[i][j-1], dp[i-1][j]);
}
}
return dp[n][n];
}
};
// { Driver Code Starts.
int main(){
string str;
cin >> str;
Solution obj;
int ans = obj.LongestRepeatingSubsequence(str);
cout << ans << "\n";
return 0;
} // } Driver Code Ends