Longest Repeating Subsequence

Description

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., any ith character in the two subsequences shouldn’t have the same index in the original string.

Example

Example 1:

Input:"aab"
Output:1
Explanation:
The two subsequence are a(first) and a(second). 
Note that b cannot be considered as part of subsequence as it would be at same index in both.

Example 2:

Input:"abc"
Output:0
Explanation:
There is no repeating subsequence
思路:动态规划。
dp[i][j] 代表前i个与前j个匹配的最大长度。
若字符相同而位置不同,即可转移。
public class Solution {
    /**
     * @param str: a string
     * @return: the length of the longest repeating subsequence
     */
    public int longestRepeatingSubsequence(String str) {
       int n = str.length();

        int[][] dp = new int[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.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][j - 1], dp[i - 1][j]);
            }
        }
        return dp[n][n];
    }
}

  

猜你喜欢

转载自www.cnblogs.com/FLAGyuri/p/12078298.html