LintCode 581: Longest Repeating Subsequence (DP经典题)

本文探讨了如何寻找一个字符串中最长的重复子序列,确保两个子序列在原字符串中不共享相同位置的字符。通过动态规划算法实现,提供两种矩阵实现方式,详细解释了算法流程及关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 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., 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

解法1:DP。
注意:
1) 当str[i]==str[j] && i == j时,也要到else分支。
2) 用n+1*n+1矩阵比较方便。

class Solution {
public:
    /**
     * @param str: a string
     * @return: the length of the longest repeating subsequence
     */
    int longestRepeatingSubsequence(string &str) {
        int n = str.size();
        if (n == 0) return 0;
        
        vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));
        for (int i = 1; i <= n; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (str[i - 1] == str[j - 1] && i != j) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        
        return dp[n][n];
    }
};

另一种写法是只用n*n的矩阵,稍微繁琐一点。代码如下:

class Solution {
public:
    /**
     * @param str: a string
     * @return: the length of the longest repeating subsequence
     */
    int longestRepeatingSubsequence(string &str) {
        int n = str.size();
        if (n == 0) return 0;
        
        vector<vector<int>> dp(n, vector<int>(n, 0));
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                if (str[i] == str[j] && i != j) {
                    if (i > 0 && j > 0) dp[i][j] = dp[i - 1][j - 1] + 1;
                    else dp[i][j] = 1;
                } else {
                    if (i > 0 && j > 0) dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                    else if (i == 0 && j > 0) dp[0][j] = dp[0][j - 1];
                    else if (i > 0 && j == 0) dp[i][0] = dp[i - 1][0];
                }
            }
        }
        
        return dp[n - 1][n - 1];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值