Longest Repeating Subsequence

Given a string, find length of the longest repeating subsequence such that the two subsequence don’t have same string character at same position, i.e., anyithcharacter in the two subsequences shouldn’t have the same index in the original string.

Example

str =abc, return0, There is no repeating subsequence

str =aab, return1, The two subsequence area(first) anda(second).
Note thatbcannot be considered as part of subsequence as it would be at same index in both.

str =aabb, return2

public int longestRepeatingSubsequence(String str) {
    if(str == null || str.length() == 0) {
        return 0;
    }
    int len = str.length();
    int[][] dp = new int[len + 1][len + 1];
    dp[0][0] = 0;
    for(int i = 1; i <= len; i++) {
        dp[i][0] = 0;
    }
    for(int i = 1; i <= len; i++) {
        dp[0][i] = 0;
    }
    for(int i = 1; i <= len; i++) {
        char c1 = str.charAt(i - 1);
        for(int j = 1; j <= len; j++) {
            char c2 = str.charAt(j - 1);
            if(c1 == c2 && i != j) {
                //length plus 1
                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[len][len];
}

results matching ""

    No results matching ""