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

被折叠的 条评论
为什么被折叠?



