码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Repeating Subsequence

时间:2019-12-21 22:26:52      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:tput   exp   思路   rip   不同   amp   any   highlight   origin   

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];
    }
}

  

Longest Repeating Subsequence

标签:tput   exp   思路   rip   不同   amp   any   highlight   origin   

原文地址:https://www.cnblogs.com/FLAGyuri/p/12078298.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!