The Longest Repeated Subsequence (LRS) problem is to find the longest subsequence that appears more than once in a given string. For example, in the string "ABAB", the longest repeated subsequence is "AB" because it appears twice.
Dynamic programming can be used to solve the LRS problem efficiently in O(n2), where n is the length of the string. The basic idea of dynamic programming is to break down the problem into smaller subproblems and solve each subproblem only once, storing the solutions in a table for later use.
We can define a 2D table dp[][] where dp[i][j] represents the length of the longest repeated subsequence of the first i characters of the string, considering the j characters. For example, if we have the string "ABCA", then dp[3][2] would represent the length of the longest repeated subsequence considering the first three characters "ABC" and the first two characters "AB".
To fill in the dp table, we can use the following recurrence relation:
If the i-th and j-th characters of the string are the same and i!=j:
dp[i][j] = dp[i-1][j-1] + 1
If the i-th and j-th characters of the string are not the same:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
The first case occurs when we find a character that matches a character that we have seen before. In this case, we can take the length of the longest repeated subsequence that we have found so far (dp[i-1][j-1]) and add 1 to it to include the matching character.
The second case occurs when we do not find a matching character. In this case, we take the maximum of the length of the longest repeated subsequence considering the i-th character of the first string and the j-th character of the second string (dp[i-1][j]) and the length of the longest repeated subsequence considering the i-th character of the first string and the j-th-1 character of the second string (dp[i][j-1]).
The final answer to the LRS problem is the value in dp[n][n] where n is the length of the string.
Here’s the Java code for implementing the dynamic programming approach to solve the LRS problem:
public static int lrs(String str) {
int n = str.length();
int[][] dp = new int[n+1][n+1];
// Fill in the dp table
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (str.charAt(i-1) == str.charAt(j-1) && i != j) {
dp[i][j] = dp[i-1][j-1] + 1;
} else {
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
}
}
return dp[n][n];
}